Created
August 15, 2014 09:37
-
-
Save iaintshine/c288d643a8c5ca60d5de to your computer and use it in GitHub Desktop.
A Ruby implementation of a Quicksort Algorithm
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
require 'test/unit' | |
module Sort | |
extend self | |
def quicksort(container) | |
return container if container.size < 2 | |
pivot = container.size / 2 | |
e = container[pivot] | |
container.delete_at pivot | |
lesser = [] | |
greater = [] | |
container.each { |item| item < e ? lesser << item : greater << item } | |
quicksort(lesser) + [e] + quicksort(greater) | |
end | |
end | |
if __FILE__ == $0 | |
class TestQuicksort < Test::Unit::TestCase | |
def setup | |
@unsorted = [3, 5, 2, 4, 6, 1] | |
@sorted = [1, 2, 3, 4, 5, 6] | |
end | |
def test_mergesort | |
assert_equal @sorted, Sort.quicksort(@unsorted) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment