Giannis D
Giannis D

Reputation: 39

How to sort two-dimensional array using qsort() in C

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.

Upvotes: 0

Views: 819

Answers (1)

rcgldr
rcgldr

Reputation: 28826

C doesn't allow the assignment of arrays. You could create an array of pointers, sort the pointers according to one of the arrays, the reorder the arrays according to the pointers using memcpy or a loop to move rows (the link below shows an efficient way to do this). (Using an array of indexes would require the compare function to be able to reference an array's elements only given the indexes.)

The second part of the answer in this thread shows the pointer method. For qsort(), the compare function input parameters would be pointer to pointer to (the first integer of a) row.

Sorting two arrays based on one with standard library (copy steps avoided)

An alternative would be to use structures, where each structure contains an array, since C does allow structures to be assigned.

Upvotes: 2

Related Questions