Ruby實現的各種排序演算法
阿新 • • 發佈:2019-02-16
def quick_sort(a)
(x=a.pop) ? quick_sort(a.select{|i| i <= x}) + [x] + quick_sort(a.select{|i| i > x}) : []
end
def first_number(n)
(n * 10).to_i
end
def bucket_sort(a)
tmp = []
(0..9).each do |j|
tmp[j] = []
end
a.each do |n|
k = first_number(n)
tmp[k] << n
end
(0..9).each do |j|
tmp[j] = quick_sort(tmp[j])
end
tmp.flatten
end
a = [0.75, 0.13, 0, 0.44, 0.55, 0.01, 0.98, 0.1234567]
p bucket_sort(a)
# Result:
[0, 0.01, 0.1234567, 0.13, 0.44, 0.55, 0.75, 0.98]