This is how I would implement quick sort in Ruby:
def quicksort(*ary)
return [] if ary.empty?
pivot = ary.delete_at(rand(ary.size))
left, right = ary.partition(&pivot.:>)
return *quicksort(*left), pivot, *quicksort(*right)
end
Actually, I would probably make it an instance method of Array
instead:
class Array
def quicksort
return [] if empty?
pivot = delete_at(rand(size))
left, right = partition(&pivot.:>)
return *left.quicksort, pivot, *right.quicksort
end
end
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…