# arbitrary sort algorithm

• April 5th, 2013, 07:15 PM
Jarwulf
arbitrary sort algorithm
Hi, does anyone know of a C++ sort algorerhythm or library that can take input of a bunch of rows of data and then sort rows by an arbitrary defined order of one of the columns

ie sort rows by value of the first column in this order (boba bobc bobe bobx) etc?
• April 7th, 2013, 02:08 AM
nuzzle
Re: arbitrary sort algorithm
Quote:

Originally Posted by Jarwulf
a C++ sort algorerhythm or library that can take input of a bunch of rows of data and then sort rows by an arbitrary defined order of one of the columns

You can quite easily sort a 2D-array using the standard C++ sort algorithm. If the 2D-array has a normal C++ memory layout it's most efficient to first create an array holding pointers to the rows. Then this row pointer array is sorted using a sort criterion which decides the pairwise order between row pointers based on row contents. Finally the original 2D-array is copied to a new 2D array according to the sorted row order available in the row pointer array. Alternatively you do this in-place in the original using some swapping scheme.

Note that if the 2D-array often is handled row-wise it may be convenient not to use the standard C++ memory layout, but to switch to a 1D-array-of-pointers-pointing-to-1D-arrays-of-elements data structure. This very much simplifies the sorting process described above because the row pointer array now already exists as part of the 2D-array.