如何在Ruby中手动缩写字母?没有sort或sort_by方法

时间:2019-05-04 12:06:22

标签: ruby sorting

对字母数组进行排序时,sortsort_by方法在Ruby中如何工作?

在不使用内置方法sortsort_by的情况下如何手动操作?

示例:

irb(main):036:0> array = ['a','e','b','d','c']
=> ["a", "e", "b", "d", "c"]
irb(main):037:0> array.sort
=> ["a", "b", "c", "d", "e"]

2 个答案:

答案 0 :(得分:1)

如果没有重复的元素:

arr = ['a','e','b','d','c']

('a'..'z').to_a & arr
  #> ["a", "b", "c", "d", "e"]

如果可能存在重复的元素:

arr = ['a','e','c','b','d','e','c']

h = arr.each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }
  #=> {"a"=>1, "e"=>2, "c"=>2, "b"=>1, "d"=>1} 
(('a'..'z').to_a & arr).flat_map { |s| [s]*h[s] }
  #=> ["a", "b", "c", "c", "d", "e", "e"] 

注意:

  • 文档Array#&指出:“订单保留在原始数组中”。
  • ('a'..'z').to_a & arr('a'..'z').to_a & arr.uniq相同。

答案 1 :(得分:0)

也许您可以编写自己的算法?

def custom_sort(ary)
  start_ = []
  end_ = []
  loop do
    break if ary.size <= 1
    a, b = ary.min, ary.max
    start_ << ary.delete_at(ary.index(a))
    end_ << ary.delete_at(ary.index(b))
  end
  start_ << ary[0] unless ary.empty?
  start_ + end_.reverse
end

ary = ['a','e','b','d','c','a','a']
custom_sort(ary) #=> ["a", "a", "a", "b", "c", "d", "e"]