I have an 1D array containing a set of rankings. e.g.
0|0
1|2
2|2
3|1
4|0
5|1
(the first column shown here is the array index)
which i’d like to rank like so
1|2
2|2
3|1
5|1
0|0
4|0
Notice that the indexes stay in numerically ascending order when there is a tie. What sort of algorithm should I be looking at to do this?
As other posters have answered, you probably want a stable sort. Stable sorting algorithms include
If I was to choose, I would probably go with merge sort because it has the best complexity. Insertion sort can beat it on small lists though. I remember reading that there’s one case where Bubble Sort isn’t terrible but I forget what it is.
However, it’s worth noting that worrying about stability will rule out an algorithm like quicksort which may be the algorithm that your unspecified language uses in its sorting functions.
Whatever language you’re using, its sort implementation should be able to take a function that will compare two items and establish which one is “greater”. So all you really need to do is write a function which
This is just sorting the items ‘lexicographically’ using whatever sort algorithm comes with the language and removes the need for stability assuming that you can consider two items to be equal if they have the same index.
The precise protocol that this function follows will vary from language to language.