Reading preferences
Concept

Merge Sort

Sort smaller halves, then merge them into one ordered row.

merge sort, sorting, divide and conquer, stable

Join two ordered piles

Imagine two piles of number cards, each already arranged smallest first. Compare the first card of each pile and take the smaller one. Repeat until both piles are empty. The new pile is ordered too.

Merge sort uses divide and conquer: split a row, sort both halves, then merge the sorted halves.

Why use it and where it helps

Merge sort gives predictable O(n log n) time even when the input is already ordered or in reverse order. Merging ordered streams is useful when working with data too large to treat as a single in-memory row, though external sorting needs additional storage and careful input/output handling.

Follow an example

       [4, 1, 3, 2]
       /          \
   [4, 1]       [3, 2]
   /   \         /   \
 [4]  [1]      [3]  [2]
   \   /         \   /
   [1, 4]       [2, 3]
        \        /
       [1, 2, 3, 4]

The final merge compares 1 with 2, then 4 with 2, then 4 with 3. Once the right side is empty, the remaining 4 is added.

See the reasoning

Follow the example one step at a time

Split the example and merge its ordered halves. This is a prepared teaching demonstration, not live code execution.

Start

[4, 1, 3, 2]

The row is not yet ordered.

Python illustration

def merge_sort(numbers):
    if len(numbers) <= 1:
        return numbers[:]
    middle = len(numbers) // 2
    left = merge_sort(numbers[:middle])
    right = merge_sort(numbers[middle:])
    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([4, 1, 3, 2]))
print(merge_sort([]))

Prepared output — not live execution:

[1, 2, 3, 4]
[]

The function returns a new list and does not change the input. When two items compare equal, choosing from the left first preserves their original relative order: this is called stability.

Time, space, and common mistakes

For n items, balanced splitting makes O(log n) levels, and merging takes O(n) work per level, giving O(n log n) time. This implementation uses O(n) extra space at peak plus O(log n) recursive stack depth. Stability depends on the tie rule; taking the right equal item first would change it.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does merge sort do before merging?
2. When merging two sorted rows which available item should come next?
3. What does this implementation return for an empty row?
4. Does this implementation sort without creating lists?

References and further reading