Created
December 25, 2012 18:46
-
-
Save hamakn/4374757 to your computer and use it in GitHub Desktop.
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(arr) | |
return arr if arr.size <= 1 | |
pivot = arr.last | |
f, l = 0, arr.size - 1 | |
loop do | |
loop { break if arr[f].nil? || arr[f] > pivot; f += 1 } | |
loop { break if arr[l].nil? || arr[l] < pivot; l -= 1 } | |
break if l < f | |
arr[f], arr[l] = arr[l], arr[f] | |
end | |
return [quicksort(arr[0..l]), pivot, quicksort(arr[f..arr.size-2])].flatten | |
end | |
require "rspec" | |
describe "quicksort" do | |
it do | |
arr = 1.upto(1000).map{|i| i}.shuffle | |
arr.sort == quicksort(arr) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment