I’m trying to figure out the best way to sort an array under multiple criteria. I want to sort an array, then sort a subset of that array if they were equal under the first criteria.
Example:
Say we have the data: { ("cat", 2), ("dog", 4), ("cat", 1), ("dog", 3) }
We sort this first according to alphabetical order of the string:
{ ("cat", 2), ("cat", 1), ("dog", 4), ("dog", 3) }
Then we sort the two subsets (set of cats and the set of dogs) in increasing order of their numbers:
{ ("cat", 1), ("cat", 2), ("dog", 3), ("dog", 4) }
Also, I’m using a recursive quicksort method that has the following header:
void quickSort(vector<Type*>, int left, int right)
where left and right are the bounding indices by which the vector should be sorted.
Should I add code to the sorting method itself or should i call the sorting method again somehow?
Generally, you want a custom comparator to sort with.
If you can’t just use a single custom operator, you can use a stable sort.
As pointed out by Mark,
std::sortis not a stable sort. Instead you would need to usestd::stable_sort.You want to sort them independently in order of increasing importance. So, you sort by numbers and then by the string.
You would prefer the first obviously, but the latter can come in handy for keeping combinatorial and/or run-time configurable algorithms simplistic.
For reference:
cplusplus.com C++ : Reference : STL Algorithms : stable_sort
cplusplus.com C++ : Reference : STL Algorithms : sort