arbitrary sort function

Started by
3 comments, last by iMalc 11 years ago

Hi, does anyone know of a C++ sort algorithm or library that can take input of a bunch of rows and sort rows by an arbitrary defined order of such as

ie sort rows by first column in this order (boba bobc bobe bobx) etc?

Advertisement
Std::sort is designed for this - the 3rd parameter is the ordering/comparison function to use.

**sorry no example, I'm posting from my phone, google should have some ;)**

Std::sort is designed for this - the 3rd parameter is the ordering/comparison function to use.

**sorry no example, I'm posting from my phone, google should have some ;)**

I see plenty of examples with simple stuff like arrays but I don't really see examples of how std:sort can work on arranging rows of a big input file let alone arranging them based on the value of a specific column in a predefined order ie (Z, X, A, B) .

Sorting is typically done in memory, and Hodgman's answer is perfectly fine.

If you are interested in sorting files that are so large that they don't fit in memory, look up external sorting. But I very much doubt that's what you want
To clarify, it's not a special sorting algorithm you want, virtually all of them can do this. std::sort or std::stable_sort are fine for this.

What you want is special comparison and exchanging functionality. Even then, this sort of thing is not that uncommon.
In order to have it run-time configurable, you may be best to declare a comparator that takes a list of column IDs in its constructor, and whose () operator uses that accordingly. If you don't need to change the order the columns are sorted by at run-time then its even easier, and a very common thing to do.
Then it's just a matter of ensuring it swaps 'rows' correctly, probably via writing a custom swap function for your 'row' class.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement