Created
February 27, 2012 04:50
-
-
Save kentor/1921482 to your computer and use it in GitHub Desktop.
Ruby Quicksort Implementation (In-Place)
This file contains hidden or 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
class Array | |
def qsort!(low = 0, high = self.size - 1) | |
return self if high <= low | |
pivot_idx = rand(low..high) | |
pivot = self[pivot_idx] | |
self[pivot_idx], self[high] = self[high], pivot | |
i, j = low - 1, high | |
begin | |
begin i += 1 end while self[i] < pivot | |
begin j -= 1 end while self[j] > pivot && j > low | |
self[i], self[j] = self[j], self[i] if i < j | |
end while i < j | |
self[high] = self[i] | |
self[i] = pivot | |
qsort!(low, i - 1) | |
qsort!(i + 1, high) | |
end | |
def qsort | |
dup.qsort! | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment