How do I do stable sort?

落花浮王杯 提交于 2019-11-30 05:00:30

问题


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 have worked best for me.

Example:

a = [[:a, 0], [:b, 1], [:c, 0], [:d, 0]]
a.sort_by { |x, y| y }  # => [[:a, 0], [:d, 0], [:c, 0], [:b, 1]]

Looking for

[[:a, 0], [:c, 0], [:d, 0], [:b, 1]]

回答1:


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]]


来源:https://stackoverflow.com/questions/21927006/how-do-i-do-stable-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!