# [Solved] Matrix sorting in C

``````#include <stdio.h>
#include <stdlib.h>

typedef int(*comparer) (int a, int b);

int compareasc ( const void *pa, const void *pb ) {
const int *a = *(const int **)pa;
const int *b = *(const int **)pb;
if(a[0] == b[0])
return a[1] - b[1];
else
return a[0] - b[0];
}
int comparedsc ( const void *pa, const void *pb ) {
const int *a = *(const int **)pa;
const int *b = *(const int **)pb;
if(a[2] == b[2])
return b[1] - a[1];
else
return b[2] - a[2];
}

int main(void){
int **array,**array2;
//  int 8 = 10;
//int i;
int pid[8],priority[8],arrival[8];
FILE *fp;
char buff[255];
fp = fopen("process.rtf","r");
if(fp ==NULL)
else{
int i =0;
while(fgets(buff,100,fp)!=NULL){
sscanf(buff,"%d  %d  %d",&pid[i],&arrival[i],&priority[i]);
i++;
}
fclose(fp);
}
for(int i=0;i<8;i++){
pid[i] = pid[i+1];
priority[i]=priority[i+1];
arrival[i] = arrival[i+1];
}
/*
* Sorting the dataset in Ascending order based on the Arrival time
*/
array = malloc(8 * sizeof(int*));
for (int i = 0; i < 8; i++){
array[i] = malloc(2 * sizeof(int));
array[i][0] = pid[i];
array[i][1] = arrival[i];
array[i][2] = priority[i];
}
printf("The original dataset\n");
for(int i = 0;i < 7;++i)
printf("%2d %2d %2d\n", array[i][0], array[i][1],array[i][2]);

printf("\n");

printf("Dataset sorted based on the arrival in ascending order:\n");
qsort(array, 8, sizeof array[2], compareasc);

for(int i = 1;i < 8;++i)
printf("%2d %2d %2d\n", array[i][0], array[i][1],array[i][2]);

/*--------------------------------------------------*/
/*
* Sorting the dataset in Desceding order based on the priority
*/
printf("\n");
array2 = malloc(8 * sizeof(int*));
for (int i = 0; i < 8; i++){
array2[i] = malloc(2 * sizeof(int));
array2[i][0] = pid[i];
array2[i][1] = arrival[i];
array2[i][2] = priority[i];
}
printf("Original Dataset:\n");
for(int i = 0;i < 7;++i)
printf("%2d %2d %2d\n", array2[i][0], array2[i][1],array2[i][2]);

printf("\n");
printf("Dataset sorted based on priority in descending order:\n");
qsort(array2, 8, sizeof array2[2], comparedsc);

for(int i = 1;i < 8;++i)
printf("%2d %2d %2d\n", array2[i][0], array2[i][1],array2[i][2]);

return 0;
}
``````

solved Matrix sorting in C