Created
April 5, 2018 23:07
-
-
Save bparanj/807ef4042f0966b2a1e0dedc9858f26f to your computer and use it in GitHub Desktop.
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
def quick_sort(array, first, last) | |
if first < last | |
q = partition(array, first, last) | |
quick_sort(array, first, q) | |
quick_sort(array, q+1, last) | |
end | |
array | |
end | |
def partition(array, low_index, high_index) | |
i = low_index - 1 | |
j = high_index + 1 | |
pivot = array[low_index] | |
loop do | |
begin | |
i += 1 | |
break if i == high_index | |
end until array[i] >= pivot | |
begin | |
j -= 1 | |
break if j == low_index | |
end until array[j] <= pivot | |
# break the loop if pointers cross | |
break if i >= j | |
array[i], array[j] = array[j], array[i] | |
end | |
return j | |
end | |
p quick_sort([7,3,11,1,2,6,10,8,9,4,5],0,10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment