Suppose I have a list of things (numbers, to keep things simple here) and I have a function I want to use to sort them by, using SortBy. For example, the following sorts a list
This seems to work:
stableSortBy[list_, f_] :=
SortBy[MapIndexed[List, list], {f@First[#], Last[#]}&][[All,1]]
But now I see rosettacode gives a much nicer way to do it:
stableSortBy[list_, f_] := list[[Ordering[f /@ list]]]
So Ordering is the key! It seems the Mathematica documentation makes no mention of this sometimes-important difference Sort and Ordering.