Sorting a 2 dimensional array on multiple columns

2020-07-18 09:53发布

问题:

I need to sort a 2 dimensional array of doubles on multiple columns using either C or C++. Could someone point me to the algorithm that I should use or an existing library (perhaps boost?) that has this functionality?

I have a feeling that writing a recursive function may be the way to go but I am too lazy to write out the algorithm or implement it myself if it has been done elsewhere. :-)

Thanks

回答1:

You can use std::sort (C++) or qsort (C or C++) to perform the sorting operation. The tricky part is that you need to define a custom comparison function for comparing your rows. For example:

 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);
 // ...


回答2:

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);