Last active
January 1, 2016 23:08
-
-
Save yoshikischmitz/8214226 to your computer and use it in GitHub Desktop.
Simple quicksort in Ruby, just as an exercise.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def quicksort(array, first = true) | |
if first == true | |
# if this is the first time quicksort is invoked | |
# we have to de-reference the array, as we use the | |
# destructive method delete_at | |
array = array.dup | |
end | |
if array.size <= 1 | |
return array | |
end | |
pivot = array[rand(array.size)] | |
array.delete_at(array.index(pivot)) | |
less, greater = [], [] | |
array.each do |x| | |
if x <= pivot | |
less << x | |
else | |
greater << x | |
end | |
end | |
return [quicksort(less, false), pivot, quicksort(greater, false)].flatten | |
end | |
@array = Array.new(9).map { rand(99) } | |
puts "Unsorted array:\t#{@array}" | |
@sorted_array = quicksort(@array) | |
puts "Sorted array:\t\t#{@sorted_array}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment