Skip to content

Instantly share code, notes, and snippets.

@sarogers
Created May 6, 2012 03:45
Show Gist options
  • Save sarogers/2609602 to your computer and use it in GitHub Desktop.
Save sarogers/2609602 to your computer and use it in GitHub Desktop.
An in-place implementation of quicksort in Ruby.
def my_quicksort(array)
left = 0
right = array.length - 1
quicksort(array, left, right)
end
def quicksort(array, left, right)
if left < right
pivot_index = ((right + left).to_f / 2).ceil
pivot_new_index = partition(array, left, right, pivot_index)
quicksort(array, left, pivot_new_index - 1)
quicksort(array, pivot_new_index + 1, right)
end
array
end
def partition(array, left, right, pivot_index)
pivot_value = array[pivot_index]
array[pivot_index], array[right] = array[right], array[pivot_index]
store_index = left
(left..(right - 1)).each do |i|
if array[i] < pivot_value
array[i], array[store_index] = array[store_index], array[i]
store_index += 1
end
end
array[store_index], array[right] = array[right], array[store_index]
store_index
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment