
This article is part of a series adapted and expanded from my Medium article, published August 5, 2024, and my merge sort repository.
The first lesson introduced splitting and merging. Here we turn that idea into code and look at its cost.

Follow the animation step by step
The animation starts with two sorted runs, [3, 8] and [1, 5], plus an empty output buffer. The two pointers mark the next value to compare in each input.
- Compare 3 and 1: take 1, because it is smaller. The output becomes [1]. The pointer in the right run moves to 5.
- Compare 3 and 5: take 3. The output becomes [1, 3], and the left pointer moves to 8. The left value wins this tie rule when values are equal, which is what keeps the merge stable.
- Compare 8 and 5: take 5. The output becomes [1, 3, 5]. The right run is now empty.
- Copy what remains: append 8 without more comparisons. The completed output is [1, 3, 5, 8].
Each input pointer only moves forward. Every value is copied once, so merging two runs with a total of n values takes O(n) time and needs an output buffer.

Algorithm and implementation
For an inclusive range from low to high, the recursive outline is:
mergeSort(values, low, high):
if low >= high:
return
mid = low + (high - low) / 2
mergeSort(values, low, mid)
mergeSort(values, mid + 1, high)
merge(values, low, mid, high)Here is a complete Python example that returns a new list:
def merge_sort(values):
if len(values) <= 1:
return values[:]
mid = len(values) // 2
left = merge_sort(values[:mid])
right = merge_sort(values[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
print(merge_sort([8, 3, 5, 1])) # [1, 3, 5, 8]The <= comparison chooses the left item first when values are equal. If equal keys represent different records, this preserves their original order, making this implementation stable.
Time and space costs
For n elements, a balanced split produces about log₂ n levels. At each level, merging processes up to n elements. This gives merge sort O(n log n) time in the best, average, and worst cases. The usual array implementation uses O(n) extra space for merging and O(log n) recursion stack space. The sample also creates slices and new lists, so it makes additional allocations.
Merge sort is useful when predictable running time and stable ordering matter. The extra memory can be a drawback for large in-memory arrays. An iterative version avoids recursion, but it still needs merge storage in the usual array implementation.


