Skip to content

Instantly share code, notes, and snippets.

@rringler
Created September 30, 2018 20:29
Show Gist options
  • Save rringler/679d5ff76713d69aadfc36d0e0303c36 to your computer and use it in GitHub Desktop.
Save rringler/679d5ff76713d69aadfc36d0e0303c36 to your computer and use it in GitHub Desktop.
Quicksort (Ruby)
def quicksort(array, left = 0, right = nil)
right ||= array.size - 1 # Sort the whole array be default
# NOTE: This is subtle; we only need to perform the sorting if `left` is less
# than `right`
if left < right
index = sort(array, left, right)
quicksort(array, left, index - 1) # Sort left sub_array
quicksort(array, index + 1, right) # Sort right sub_array
end
array
end
def sort(array, left, right)
wall = index = left
pivot = array[right]
# NOTE: This is subtle; we only iterate through if there are elements to be
# sorted
while(index < right) do
if array[index] < pivot
# NOTE: Unsorted element found: We need to swap the `index` & `wall`
# elements, and increment `wall`
array[index], array[wall] = array[wall], array[index]
wall += 1
end
index += 1
end
# NOTE: Swap the `pivot` & `wall` elements
array[wall], array[right] = array[right], array[wall]
# NOTE: Return the `wall` index (so we can further divide the array for
# sorting)
wall
end
puts "sorted: #{quicksort((1..10).to_a.shuffle)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment