Skip to content

Instantly share code, notes, and snippets.

@mac-r
Created June 25, 2013 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mac-r/5856464 to your computer and use it in GitHub Desktop.
Save mac-r/5856464 to your computer and use it in GitHub Desktop.
quick sort
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