Stable Sorting, ie, Minimally-Disruptive Sorting

后端 未结 4 1144
囚心锁ツ
囚心锁ツ 2021-02-02 14:29

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

4条回答
  •  一个人的身影
    2021-02-02 14:50

    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.

提交回复
热议问题