How do I do stable sort?

前端 未结 1 1499
旧时难觅i
旧时难觅i 2021-01-05 16:01

How do I stably sort an array? The value I want to sort by can have a lot of duplicates, and I\'m not sure which sort algorithm ruby uses. I\'m thinking insertion sort would

相关标签:
1条回答
  • 2021-01-05 16:21

    Put the key that you originally wanted to sort by and the index into an array, and sort by that.

    a.sort_by.with_index { |(x, y), i| [y, i] }
      # => [[:a, 0], [:c, 0], [:d, 0], [:b, 1]]
    
    0 讨论(0)
提交回复
热议问题