I want to sort the two-dimensional array of integers "d" according to the first column in decreasing order, using qsort(). However, I want each element of the first column to match the element that was in the second column in the same line on the beginning.
For example:
Array in the beginning:
column1: { 4, 5, 1, 3, 0}
column2: { 1, 2, 3, 4, 5}
and the result should be:
column1: { 5, 4, 3, 1, 0}
column2: { 2, 1, 4, 3, 5}
I have written the code for sorting an one-dimensional array, but I can't figure out how to do that for the two-dimensional one.
int main(){
FILE *file_in, *file_out;
file_in=fopen("file.in", "r");
fscanf(file_in, "%d", &N);
for( i = 1; i <= N; i = i + 1 ){
fscanf(file_in, "%d", &a);
fscanf(file_in, "%d", &b);
fscanf(file_in, "%d", &c);
d[i][1] = a+b+c;
d[i][2] = a*b*c
}
fclose(file_in);
int cmpfunc (const void * a, const void * b) {
return ( *(int*)b - *(int*)a );
}
qsort(d, N, sizeof(int), cmpfunc);
file_out=fopen("file.out","w");
fprintf(file_out, "%d", M);
for ( i=1; i<=N; i = i + 1){
fprintf(file_out, "%d", d);
}
fclose(file_out);
return 0;
}
Thank you in advance for your help.