Skip to content

Instantly share code, notes, and snippets.

@sirmxanot
Created October 25, 2012 22:00
Show Gist options
  • Save sirmxanot/3955719 to your computer and use it in GitHub Desktop.
Save sirmxanot/3955719 to your computer and use it in GitHub Desktop.
merge sort ruby
def merge_sort(m)
#base case
if m.length <= 1
return m
else
#intialize variables
left = Array.new
right = Array.new
middle = m.length/2
#split first half to left and second half to right
left = merge_sort(m[0..middle-1])
right = merge_sort(m[middle..-1])
merge = merge(left, right)
return merge
end
end
def merge(left, right)
output = Array.new
i = 0
j = 0
for k in (0..(left.length+right.length-1))
if i < left.length && j < right.length
if left[i] < right[j]
output[k]=left[i]
i+=1
else
output[k]=right[j]
j+=1
end
elsif i >= left.length && j < right.length
output[k]=right[j]
j+=1
elsif i < left.length && j >= right.length
output[k]=left[i]
i+=1
end
end
return output
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment