Skip to content

Instantly share code, notes, and snippets.

@omedale
Last active April 12, 2019 17:30
Show Gist options
  • Select an option

  • Save omedale/7af9981a094e93bb235cffc470c4b818 to your computer and use it in GitHub Desktop.

Select an option

Save omedale/7af9981a094e93bb235cffc470c4b818 to your computer and use it in GitHub Desktop.
Ruby Implementation of Quick Sort
def quick_sort(array)
return array if array.size <= 1
# select a pivot element
# here we get the first element of the array
pivot ||= array.shift
#use the pivot to break down the array into 2 subarray(left and right)
left = array.select { |n| n < pivot }
right = array.select { |n| n >= pivot }
# recursively call quick_sort with the left and right array
# then pick a pivot
# if pivot is larger than the value to the right
# switch their positions.
return [*quick_sort(left), pivot, *quick_sort(right)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment