Skip to content

Instantly share code, notes, and snippets.

@willasaywhat
Created September 3, 2009 19:22
Show Gist options
  • Save willasaywhat/180480 to your computer and use it in GitHub Desktop.
Save willasaywhat/180480 to your computer and use it in GitHub Desktop.
Merge sort implemented in Ruby
def merge_sort(m)
if m.length <= 1
return m
end
middle = m.length / 2 - 1
left = m[0..middle]
right = m[middle+1..m.length]
left = merge_sort(left)
right = merge_sort(right)
if left.last > right.first
result = merge(left, right)
else
result = left.concat(right)
end
return result
end
def merge(left, right)
result = []
while left.length > 0 and right.length > 0
if left.first <= right.first
result << left.shift
else
result << right.shift
end
end
if left.length > 0
result.concat(left)
else
result.concat(right)
end
return result
end
begin
list = [1,4,5,7,8,56,32,32,43,43545,67676,324343,5435,0,12,333,3,3,2,1,134,45,7]
tmp = merge_sort(list)
puts tmp.inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment