Sort 2-dimensional array in ANSI C with qsort ()

I have a two-dimensional array and you want to sort both rows depending on the order of the elements in the first row:

i start with:

row1: {4, 3, 1, 5, 0}

row2: {7, 8, 9, 1, 2}

and the result should be:

row1: {0, 1, 3, 4, 5}

row2: {2, 9, 8, 7, 1}

Question: Is it possible to achieve this using the qsort () function?

+6
source share
2 answers

Not directly ...

... but qsort() can sort the vectors for each vector of the first element.

So, the data of the example needs to be transferred and converted to a fake 2d array, where the root pointer points to an array of pointers, and each pointer points to a line of transferred source data.

qsort() then passed the root pointer, and the comparison function is compared with the first element of the vector. Vectors are passed to compare functions by reference.

After sorting, the result should be converted to the return path, as was done before qsort() called.

+1
source

I think it can be done.

 #include<bits/stdc++.h> using namespace std; int cmp(const void *a,const void *b) { return ((const int *)a)[0] - ((const int *)b)[0]; } int main(int argc,char *argv[]){ int list[10][2]; printf("Before sorting\n"); for(int i=0; i<10; i++){ list[i][0] = rand()%31; list[i][1] = rand()%12; printf ("list[%d][0] = %d list[%d][1] = %d\n", i, list[i][0], i, list[i][1]); } printf("AFTER sorting\n"); qsort(list,10,2*sizeof(int),cmp); for(int i=0; i<10; i++) printf ("list[%d][0] = %d list[%d][1] = %d\n", i, list[i][0], i, list[i][1]); return 0; } 

Output:

 Before sorting list[0][0] = 10 list[0][1] = 11 list[1][0] = 10 list[1][1] = 4 list[2][0] = 11 list[2][1] = 4 list[3][0] = 8 list[3][1] = 6 list[4][0] = 23 list[4][1] = 8 list[5][0] = 1 list[5][1] = 5 list[6][0] = 0 list[6][1] = 3 list[7][0] = 10 list[7][1] = 11 list[8][0] = 19 list[8][1] = 2 list[9][0] = 22 list[9][1] = 0 AFTER sorting list[0][0] = 0 list[0][1] = 3 list[1][0] = 1 list[1][1] = 5 list[2][0] = 8 list[2][1] = 6 list[3][0] = 10 list[3][1] = 11 list[4][0] = 10 list[4][1] = 4 list[5][0] = 10 list[5][1] = 11 list[6][0] = 11 list[6][1] = 4 list[7][0] = 19 list[7][1] = 2 list[8][0] = 22 list[8][1] = 0 list[9][0] = 23 list[9][1] = 8 
+4
source

Source: https://habr.com/ru/post/954696/


All Articles