Quick Sort in Ruby language

后端 未结 4 577
甜味超标
甜味超标 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条回答
  •  猫巷女王i
    2020-12-18 05:33

    Here is a (very) naive quicksort implementation, based on Wikipedia's simple-quicksort pseudocode:

    def quicksort(array) #takes an array of integers as an argument
    

    You need a base case, otherwise your recursive calls never terminate

    if array.length <= 1
      return array
    

    Now pick a pivot:

    else
      pivot = array.sample
      array.delete_at(array.index(pivot)) # remove the pivot
      #puts "Picked pivot of: #{pivot}"
      less = []
      greater = []
    

    Loop through the array, comparing items to pivot and collecting them into less and greater arrays.

      array.each do |x|
        if x <= pivot
          less << x
        else
          greater << x
        end
      end
    

    Now, recursively call quicksort() on your less and greater arrays.

      sorted_array = []
      sorted_array << self.quicksort(less)
      sorted_array << pivot
      sorted_array << self.quicksort(greater)
    

    Return the sorted_array and you're done.

      # using Array.flatten to remove subarrays
      sorted_array.flatten!
    

    You can test it with

    qs = QuickSort.new
    
    puts qs.quicksort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] # true
    puts qs.quicksort([5]) == [5] # true
    puts qs.quicksort([5, -5, 11, 0, 3]) == [-5, 0, 3, 5, 11] # true
    puts qs.quicksort([5, -5, 11, 0, 3]) == [5, -5, 11, 0, 3] # false
    

提交回复
热议问题