Created
November 14, 2012 20:55
-
-
Save hrp/4074749 to your computer and use it in GitHub Desktop.
Merge Sort in Ruby
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
# merge sort in ruby | |
class Array | |
def merge_sort | |
if length > 1 | |
halves = split.map do |half| | |
half.merge_sort | |
end | |
combine(*halves) | |
else | |
self | |
end | |
end | |
private | |
def split | |
half_length = length / 2 | |
[ shift(half_length), self ] | |
end | |
def combine(x, y) | |
return y if x.empty? or x.nil? | |
return x if y.empty? or y.nil? | |
if x.first < y.first | |
[x.shift] + combine(x, y) | |
else | |
[y.shift] + combine(x, y) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment