mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-28 19:58:20 +01:00
Merge pull request #7 from michellejanosi/add_algorithm
Add quicksort algorithm
This commit is contained in:
commit
1a1c1c3987
1 changed files with 15 additions and 0 deletions
15
quicksort.rb
Normal file
15
quicksort.rb
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
def quicksort
|
||||||
|
return [] if empty?
|
||||||
|
|
||||||
|
# chose a random pivot value
|
||||||
|
pivot = delete_at(rand(size))
|
||||||
|
# partition array into 2 arrays and comparing them to each other and eventually returning
|
||||||
|
# array with the pivot value sorted
|
||||||
|
left, right = partition(&pivot.method(:>))
|
||||||
|
|
||||||
|
# recursively calling the quicksort method on itself
|
||||||
|
return *left.quicksort, pivot, *right.quicksort
|
||||||
|
end
|
||||||
|
|
||||||
|
arr = [34, 2, 1, 5, 3]
|
||||||
|
p arr.quicksort
|
Loading…
Add table
Reference in a new issue