Skip to content

Instantly share code, notes, and snippets.

@jbochi
Created August 10, 2012 11:13
Show Gist options
  • Save jbochi/3313482 to your computer and use it in GitHub Desktop.
Save jbochi/3313482 to your computer and use it in GitHub Desktop.
Quicksort in Ruby for dailykata.net
# This implementation works, but it does all comparisons twice
# and is not in-place, requiring extra memory and raising
# a stack overflow for large arrays.
def quicksort(array)
return array if array.size <= 1
pivot = array.pop
less = array.select {|x| x <= pivot }
greater = array.select {|x| x > pivot }
quicksort(less) + [pivot] + quicksort(greater)
end
require "test/unit"
class TestQuickSort < Test::Unit::TestCase
def test_simple
assert_equal([1, 2, 3, 4, 5], quicksort([5, 3, 4, 1, 2]))
end
def test_random
assert_equal([1..20], quicksort([1..20].shuffle))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment