zoukankan      html  css  js  c++  java
  • Ruby版快速排序

    class Array
       def quick_sort
          return self if self.length<=1
          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'}."
    

      

  • 相关阅读:
    sql 语句总结
    linux 操作命令
    elk 相关问题总结
    windows 下命令总结
    spring 生态的区别
    电脑基本常识 cpu的认识
    git 命令总结
    reques 和session
    linux centos7 安装docker
    get和post请求
  • 原文地址:https://www.cnblogs.com/zycjwdss/p/4205641.html
Copyright © 2011-2022 走看看