Quick Sort in Ruby language

后端 未结 4 582
甜味超标
甜味超标 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:24

    here is another way to implement quicksort -- as a newbie I think it's easier to understand -- hope it helps someone :) in this implementation the pivot is always the last element in the array -- I'm following the Khan Academy course and that's where I got the inspiration from

    def quick_sort(array, beg_index, end_index)
      if beg_index < end_index
        pivot_index = partition(array, beg_index, end_index)
        quick_sort(array, beg_index, pivot_index -1)
        quick_sort(array, pivot_index + 1, end_index)
      end
      array
    end
    
    #returns an index of where the pivot ends up
    def partition(array, beg_index, end_index)
      #current_index starts the subarray with larger numbers than the pivot
      current_index = beg_index
      i = beg_index
      while i < end_index do
        if array[i] <= array[end_index]
          swap(array, i, current_index)
          current_index += 1
        end
        i += 1
      end
      #after this swap all of the elements before the pivot will be smaller and
      #after the pivot larger
      swap(array, end_index, current_index)
      current_index
    end
    
    def swap(array, first_element, second_element)
      temp = array[first_element]
      array[first_element] = array[second_element]
      array[second_element] = temp
    end
    
    puts quick_sort([2,3,1,5],0,3).inspect #will return [1, 2, 3, 5]
    

提交回复
热议问题