Skip to content

Instantly share code, notes, and snippets.

@bootcoder
Created October 21, 2015 23:36
Show Gist options
  • Select an option

  • Save bootcoder/aa4e873d77bade957927 to your computer and use it in GitHub Desktop.

Select an option

Save bootcoder/aa4e873d77bade957927 to your computer and use it in GitHub Desktop.
Sample of Quick sort
def quicksort(array, from=0, to=nil)
if to == nil
# Sort the whole array, by default
to = array.count - 1
end
if from >= to
# Done sorting
return
end
# 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 "Inconsistent state"
end
end
array[free] = pivot
quicksort array, from, free - 1
quicksort array, free + 1, to
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment