如何进行稳定排序? [英] How do I do stable sort?

查看:119
本文介绍了如何进行稳定排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何稳定地对数组排序?我要排序的值可能有很多重复项,而且我不确定ruby使用哪种排序算法.我认为插入排序最适合我.

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.

示例:

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

正在寻找

[[:a, 0], [:c, 0], [:d, 0], [:b, 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]]

这篇关于如何进行稳定排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆