2019-07-02 19:18:06 +02:00
|
|
|
def quicksort(arr)
|
|
|
|
return [] if arr.empty?
|
2017-10-01 16:20:29 +02:00
|
|
|
|
|
|
|
# chose a random pivot value
|
2019-07-02 19:18:06 +02:00
|
|
|
pivot = arr.delete_at(rand(arr.size))
|
2017-10-01 16:20:29 +02:00
|
|
|
# partition array into 2 arrays and comparing them to each other and eventually returning
|
|
|
|
# array with the pivot value sorted
|
2019-07-02 19:18:06 +02:00
|
|
|
left, right = arr.partition(&pivot.method(:>))
|
2017-10-01 16:20:29 +02:00
|
|
|
|
|
|
|
# recursively calling the quicksort method on itself
|
2021-02-07 08:05:54 +01:00
|
|
|
[*quicksort(left), pivot, *quicksort(right)]
|
2017-10-01 16:20:29 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
arr = [34, 2, 1, 5, 3]
|
2019-07-02 19:18:06 +02:00
|
|
|
p quicksort(arr)
|