saw a project of a friend of mine ( http://hugopeixoto.net/mergesort.xhtml ) and tried to spice up the ruby implementation
Created
December 27, 2009 23:15
-
-
Save locks/264442 to your computer and use it in GitHub Desktop.
Mergesort implementation
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 merge(a,b) | |
r = [] | |
r << (a.first < b.first ? a : b).shift until a.empty? or b.empty? | |
r+a+b | |
end | |
def mergesort(list) | |
return list if list.size <= 1 | |
m = list.size / 2 | |
merge( mergesort(list[0...m]), mergesort(list[m..-1]) ) | |
end | |
puts mergesort( [10, 9, 8, 5, 6, 7, 4, 3, 2, 1] ) |
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
require 'test/unit' | |
require 'mergesort' | |
ARRAY_UNSORTED = [10, 9, 8, 4, 5, 6, 7, 3, 2, 1] | |
ARRAY_SORTED = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
class MergeSortTest < Test::Unit::TestCase | |
def test_mergesort_implementation | |
assert_equal ARRAY_SORTED, mergesort(ARRAY_UNSORTED) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment