Merge Sort

Sort an array using the merge sort algorithm with O(n log n) time complexity.

Code

Algorithms
def merge_sort(a)
  return a if a.length <= 1
  mid = a.length / 2
  left, right = merge_sort(a[0...mid]), merge_sort(a[mid..])
  result = []
  until left.empty? || right.empty?
    result << (left[0] <= right[0] ? left.shift : right.shift)
  end
  result + left + right
end
merge_sort(arr)

Parameters

Array to sort

Server

More Ruby Snippets