Skip to content

Instantly share code, notes, and snippets.

@hamakn
Created December 25, 2012 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hamakn/4374757 to your computer and use it in GitHub Desktop.
Save hamakn/4374757 to your computer and use it in GitHub Desktop.
quicksort
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