Skip to content

Instantly share code, notes, and snippets.

@Mon-Ouie
Created April 27, 2013 08:47
Show Gist options
  • Save Mon-Ouie/5472366 to your computer and use it in GitHub Desktop.
Save Mon-Ouie/5472366 to your computer and use it in GitHub Desktop.
class Array
def merge_sort(&block)
return self if size < 2
block ||= lambda { |a, b| a <=> b }
half_size = size / 2
first_ary = self[0, half_size].merge_sort(&block)
second_ary = self[half_size, size].merge_sort(&block)
ary = []
first_ary.each do |elem|
while second_ary.first && block[second_ary.first, elem] < 0
ary << second_ary.shift
end
ary << elem
end
ary.concat(second_ary)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment