Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 21:52
Show Gist options
  • Save evidanary/569fccc9e28e31a984dd73b40b596b10 to your computer and use it in GitHub Desktop.
Save evidanary/569fccc9e28e31a984dd73b40b596b10 to your computer and use it in GitHub Desktop.
# Merge sort implementation with extra space
def merge_sort(array)
return array if array.size <= 1
left = array[0...array.size / 2]
right = array[array.size / 2...array.size]
merge(merge_sort(left), merge_sort(right))
end
def merge(left, right)
result = []
while left.size > 0 && right.size > 0
result << if left[0] <= right[0]
left.shift
else
right.shift
end
end
result.concat(left).concat(right)
end
merge_sort('MERGESORT'.chars)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment