Skip to content

Instantly share code, notes, and snippets.

@omedale
Last active April 12, 2019 18:18
Show Gist options
  • Select an option

  • Save omedale/ae9fff4c7c1c79b25c08b136feacf5c9 to your computer and use it in GitHub Desktop.

Select an option

Save omedale/ae9fff4c7c1c79b25c08b136feacf5c9 to your computer and use it in GitHub Desktop.
Ruby Implementation of Merge Sort
def merge_sort(array)
# set base case to allows the recursion to work and not go on indefinitely.
return array if array.size <= 1
# split the array into two
left, right = array.each_slice((array.size/2).round).to_a
# merge the mergesorted left half with the mergesorted right half.
merge = -> (left, right) {
array = []
while left.size > 0 && right.size > 0
array << (left[0] < right[0] ? left.shift : right.shift)
end
return array + left + right
}
return merge.call merge_sort(left), merge_sort(right)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment