Quick Sort in Ruby language

后端 未结 4 568
甜味超标
甜味超标 2020-12-18 05:03

I am trying to implement Quick sort in ruby but stuck in how to call recursively after the first partition of pivot. Please help me to understand on how to proceed and also

4条回答
  •  旧巷少年郎
    2020-12-18 05:35

    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
    

提交回复
热议问题