Skip to content

Instantly share code, notes, and snippets.

@hrp
Created November 14, 2012 20:55
Show Gist options
  • Save hrp/4074749 to your computer and use it in GitHub Desktop.
Save hrp/4074749 to your computer and use it in GitHub Desktop.
Merge Sort in Ruby
# 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