Created
July 6, 2019 02:36
-
-
Save korakotlee/27f11a727bc0c7f5b8f873c6d1274d9e to your computer and use it in GitHub Desktop.
ruby quicksort
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 quicksort(a, first, last) | |
if first < last | |
p_index = partition(a, first, last) | |
quicksort(a, first, p_index-1) | |
quicksort(a, p_index+1, last) | |
end | |
return a | |
end | |
def partition(a, first, last) | |
pivot = a[last] | |
p_index = first | |
for i in first...last do | |
if a[i] < pivot | |
a[i], a[p_index] = a[p_index], a[i] | |
p_index += 1 | |
end | |
end | |
a[p_index], a[last] = a[last], a[p_index] | |
return p_index | |
end | |
a = [3,4,6,7,8,9,5,6,1,7] | |
puts quicksort(a, 0, a.length-1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment