TheAlgorithms-Ruby/sorting/quicksort.rb

20 lines
531 B
Ruby
Raw Normal View History

def quicksort(arr)
return [] if arr.empty?
2017-10-01 10:20:29 -04:00
# chose a random pivot value
pivot = arr.delete_at(rand(arr.size))
2017-10-01 10:20:29 -04:00
# 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(:>))
2017-10-01 10:20:29 -04:00
# recursively calling the quicksort method on itself
2021-02-06 23:05:54 -08:00
[*quicksort(left), pivot, *quicksort(right)]
2017-10-01 10:20:29 -04:00
end
2021-02-17 02:33:19 +09:00
if $0 == __FILE__
puts 'Enter a list of numbers separated by space'
list = gets.split.map(&:to_i)
p quicksort(list)
end