Skip to content

Instantly share code, notes, and snippets.

@pdkproitf
Created July 13, 2019 11:52
Show Gist options
  • Save pdkproitf/ec20ec0432ab614dd11ffe6f51824200 to your computer and use it in GitHub Desktop.
Save pdkproitf/ec20ec0432ab614dd11ffe6f51824200 to your computer and use it in GitHub Desktop.
Implement quick sort in ruby
# Algorithms: https://www.geeksforgeeks.org/quick-sort/
def quick_sort(array)
return array if array.length <= 1
pivot = array.pop
l = -1
for i in 0...array.length
next unless array[i] < pivot
l += 1
array[i], array[l] = array[l], array[i] if l != i
end
print "#{array} \n"
if l == -1
[pivot] + quick_sort(array[0..l])
else
quick_sort(array[0..l]) + [pivot] + quick_sort(array[(l + 1)..-1])
end
end
def quick_sort_c2(array)
return array if array.length <= 1
pivot = array.pop
left = []
right = []
for i in 0...array.length
if array[i] < pivot
left << array[i]
else
right << array[i]
end
end
print "#{array} \n"
quick_sort(left) + [pivot] + quick_sort(right)
end
puts '------------------------------QUICK SORT SORT O(nlogn)--------------------------'
arr = [3,7,8,4,10,16,2,1,12]
print quick_sort(arr)
print quick_sort_c2(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment