Sort 2-dimensional array on multiple columns

I need to sort a 2-dimensional array of doubles across multiple columns using C or C ++. Can someone point me to an algorithm that I should use, or to an existing library (maybe augment it?), Which has this functionality?

I have a feeling that writing a recursive function is possible, but I'm too lazy to write an algorithm or implement it myself if it was done elsewhere. :-)

thanks

+4
source share
2 answers

You can use std::sort (C ++) or qsort (C or C ++) to perform a sort operation. The tricky part is that you need to define a custom comparison function to compare your strings. For instance:

  bool compareTwoRows(double* rowA, double* rowB){ return ( (rowA[0]<rowB[0]) || ((rowA[0]==rowB[0])&&(rowA[1]<rowB[1])) ); } // ... double** two_dimensional_array = // ... int rows = // ... number of rows ... std::sort(two_dimensional_array,two_dimensional_array+rows,&compareTwoRows); // ... 
+9
source

I used the following code:

 // Order function. Change the 2 for the column number you want to use bool compareRowsByColumn(vector<double> rowA, vector<double> rowB){ return (rowA[2] < rowB[2]); } // The sorting line. Matrix is the two dimensional vector. sort(matrix.begin(), matrix.end(), &compareRowsByColumn); 
0
source

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


All Articles