Ruby版快速排序


class Array
  def quick_sort
    return [] if self.empty?
    k = self[0]
    head = 0
    tail = self.length - 1
    while head < tail
      (tail-head).times do
        if self[tail] < k
          self[tail], self[head] = self[head], self[tail]
          break
        end
        tail = tail - 1
      end
      (tail-head).times do
        if self[head] > k
          self[tail], self[head] = self[head], self[tail]
          break
        end
        head = head + 1
      end
    end
    [*(self.slice(0, head).quick_sort), self[head], *(self.slice(head+1, self.length-head-1).quick_sort)]
  end
end

#test
test_len = 20

random_array = []
test_len.times do
  random_array << rand(100)
end

puts "random_array            = [#{random_array.join(‘, ‘)}]"

puts "random_array.quick_sort = [#{random_array.quick_sort.join(‘, ‘)}]"
puts "random_array.sort       = [#{random_array.sort.join(‘, ‘)}]"
puts "quick_sort #{(random_array.quick_sort == random_array.sort) ? "succeed" : ‘failed‘}."

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。