Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created March 20, 2013 05:44
Show Gist options
  • Save ackintosh/5202587 to your computer and use it in GitHub Desktop.
Save ackintosh/5202587 to your computer and use it in GitHub Desktop.
Mergesort in Ruby
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