Created
July 13, 2019 11:52
-
-
Save pdkproitf/ec20ec0432ab614dd11ffe6f51824200 to your computer and use it in GitHub Desktop.
Implement quick sort in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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