5

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

4
  • 4
    You can only sort on one column at a time. However, if two elements of the sorted column are equal, you CAN fall back to another secondary column... By the way, the words "I am too lazy" never come across well. Commented Jun 15, 2010 at 0:53
  • Well I have done a fair bit of coding where I know that there is NO existing code (e.g., MCMC samplers for various statistical models which extend the state of the art.). I prefer to be lazy instead of re-inventing a wheel especially in an area I am confident that there should be something out there. Commented Jun 15, 2010 at 1:00
  • 1) What order? Sort each collumn separately? Sort along rows? Along Collumns? 2) Is the minor size fixed or is it array of pointers? Commented Jun 15, 2010 at 4:37
  • 5
    good programmers are lazy programmers :) Commented Jun 15, 2010 at 7:47

2 Answers 2

10

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);
 // ...
Sign up to request clarification or add additional context in comments.

4 Comments

That should work. I knew about qsort and std::sort but never thought to extend the compare function to more than 1 column. I will implement it and will accept your answer if it works for me. Thanks for your quick reply.
You could also use std::stable_sort - just sort the array repeatedly, starting with the least significant column.
this one is the perfect answer..!! thanks @michael aaron safyan
Nick's solution is good because it generalizes to higher dimensions well! Imagine writing that comparison operator for more than two columns, it would get complicated fast
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.