首页 > 编程语言 > 详细

Ruby版快速排序

时间:2015-01-06 13:20:05      阅读:191      评论:0      收藏:0      [点我收藏+]


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‘}."

Ruby版快速排序

原文:http://www.cnblogs.com/zycjwdss/p/4205641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!