Stable Sorting, ie, Minimally-Disruptive Sorting

后端 未结 4 1143
囚心锁ツ
囚心锁ツ 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:59

    There is a variant of SortBy which breaks ties by using additional ordering functions:

    SortBy[list,{f1, f2, ...}]

    By counting ties you can thus obtain a stable sorting:

    Module[{tie = 0}, 
     SortBy[{19, 301, 201, 502, 501, 101, 300}, {Mod[#, 10] &, (tie++) &}]]
    

    yields

    {300, 301, 201, 501, 101, 502, 19}
    

提交回复
热议问题