Created
June 25, 2013 06:42
-
-
Save mac-r/5856464 to your computer and use it in GitHub Desktop.
quick sort
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, from=0, to=nil) | |
# Sort the whole array, by default | |
to = array.count - 1 if to == nil | |
# Done sorting | |
return if from >= to | |
# Take a pivot value, at the far left | |
pivot = array[from] | |
# Min and Max pointers | |
min = from | |
max = to | |
# Current free slot | |
free = min | |
while min < max | |
if free == min # Evaluate array[max] | |
if array[max] <= pivot # Smaller than pivot, must move | |
array[free] = array[max] | |
min += 1 | |
free = max | |
else | |
max -= 1 | |
end | |
elsif free == max # Evaluate array[min] | |
if array[min] >= pivot # Bigger than pivot, must move | |
array[free] = array[min] | |
max -= 1 | |
free = min | |
else | |
min += 1 | |
end | |
else | |
raise "Something went wrong..." | |
end | |
end | |
array[free] = pivot | |
quicksort array, from, free - 1 | |
quicksort array, free + 1, to | |
end | |
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].shuffle | |
# Quicksort operates inplace (i.e. in "a" itself) | |
# There's no need to reassign | |
quicksort a | |
puts "quicksort" | |
puts a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment