Skip to content

Instantly share code, notes, and snippets.

@kentor
Created February 27, 2012 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentor/1921482 to your computer and use it in GitHub Desktop.
Save kentor/1921482 to your computer and use it in GitHub Desktop.
Ruby Quicksort Implementation (In-Place)
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