Skip to content
UPEEC

Merge Sort

Divide the list in half, sort each half, then merge — always O(n log n).

Intermediate
Comments 0
def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

Guaranteed O(nlog⁡n)O(n \log n) and stable, at the cost of O(n)O(n) extra memory. Ideal for linked lists and for sorting data too big for RAM (external sorting).

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.