Created
March 20, 2013 05:44
-
-
Save ackintosh/5202587 to your computer and use it in GitHub Desktop.
Mergesort in Ruby
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
class Array | |
def merge_sort | |
return self if length <= 1 | |
a, b = self.half.map { |e| e.merge_sort } | |
merge(a, b) | |
end | |
def half | |
mid = length / 2 | |
return slice(0...mid), slice(mid..-1) | |
end | |
def merge(a, b) | |
result = [] | |
until a.empty? && b.empty? | |
result << | |
case | |
when a.empty? then b.shift | |
when b.empty? then a.shift | |
when a.first <= b.first then a.shift | |
else b.shift | |
end | |
end | |
result | |
end | |
end | |
ar = [5,3,2,7,10,2,12] | |
p ar.merge_sort | |
# [2, 2, 3, 5, 7, 10, 12] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment