Skip to content

Instantly share code, notes, and snippets.

@Nitesh-Mishra
Created September 11, 2017 19:13
Show Gist options
  • Select an option

  • Save Nitesh-Mishra/dd77488d00eb6a1efa334c422e14dc86 to your computer and use it in GitHub Desktop.

Select an option

Save Nitesh-Mishra/dd77488d00eb6a1efa334c422e14dc86 to your computer and use it in GitHub Desktop.
Quick Sort program in ruby
# quick_sort.rb
#
# $ ruby quick_sort.rb
# [1, 2, 3, 4, 5, 6, 7, 8]
def quicksort(array)
return array if array.length <= 1
pivot_index = (array.length / 2).to_i
pivot_value = array[pivot_index]
array.delete_at(pivot_index)
lesser = []
greater = []
array.each do |x|
if x <= pivot_value
lesser << x
else
greater << x
end
end
return quicksort(lesser) + [pivot_value] + quicksort(greater)
end
array = [6,5,3,1,8,7,2,4]
sorted = quicksort(array)
print sorted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment