TheAlgorithms-Ruby/Sorting/quicksort.rb
Mateus Luiz b950d3530d
Fix NoMethodError in the quicksort
The code was raising a `NoMethodError` with the description: 
`quicksort.rb:17:in `<main>': private method `quicksort' called for [34, 2, 1, 5, 3]:Array (NoMethodError)`

This commit fixes that
2019-07-02 14:18:06 -03:00

15 lines
449 B
Ruby

def quicksort(arr)
return [] if arr.empty?
# chose a random pivot value
pivot = arr.delete_at(rand(arr.size))
# partition array into 2 arrays and comparing them to each other and eventually returning
# array with the pivot value sorted
left, right = arr.partition(&pivot.method(:>))
# recursively calling the quicksort method on itself
return *quicksort(left), pivot, *quicksort(right)
end
arr = [34, 2, 1, 5, 3]
p quicksort(arr)