lou.tools
EN

Merge sort

Merge sort, step by step

Watch it sort any list, step by step, with its pseudocode and its Python.

Updated

Free, in your browser. Your lists never leave it.Privacy

8 values to sort.

Comparisons: 0Writes: 0lo = 0 · hi = 8

What happens next?

The run stops five times and asks what comes next. Answer, and it plays on.

Pseudocode and implementation

Pseudocode

  1. To sort the part of the list from lo to hi (at first, the whole list; hi is one past its end):
  2. If the part has more than one value, find its middle, mid:
  3. sort the left half, lo to mid, and the right half, mid to hi, each the same way;
  4. copy the left half aside and merge both halves into the part, from lo:
  5. While both halves have values left, compare the first of each:
  6. write the smaller one in the next position (the left one if they are equal).
  7. Copy what is left of the left half; what is left of the right half is already in place.
  8. Return the sorted list.

Python

def merge_sort(a, lo=0, hi=None):    if hi is None:        hi = len(a)    if hi - lo > 1:        mid = (lo + hi) // 2        merge_sort(a, lo, mid)        merge_sort(a, mid, hi)        left = a[lo:mid]        i, j, k = 0, mid, lo        while i < len(left) and j < hi:            if left[i] <= a[j]:                a[k] = left[i]                i += 1            else:                a[k] = a[j]                j += 1            k += 1        while i < len(left):            a[k] = left[i]            i += 1            k += 1    return a

How it works

Merge sort splits the list into two halves, sorts each half the same way, and then merges the two sorted halves into one. The splitting goes on until a part has a single value, which is already sorted: all the work happens in the merges, on the way back.

To merge, it compares the first value of each half and writes the smaller one, again and again, until one half is used up; what is left of the other goes at the end. Each level of splitting merges all n values once, and there are about log₂ n levels, so it always takes about n log₂ n comparisons, on a sorted list, a random one or a reversed one.

Its price is memory: the merge needs room for a copy of the values (this Python copies the left half). It never puts a value before an equal one from the left half, so it is stable, which is why languages use it, in variants such as Timsort, to sort lists of records.

Complexity

Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n log n)
Extra spaceO(n)
StableYes
In placeNo

n is how many values the list has.

Questions

When is merge sort a good choice?
When you need a predictable time whatever the input, or a stable sort, and can spare the memory for a copy. It also suits data too big for memory, read in sorted runs and merged, and linked lists, where it needs no copy.
How is it different from quicksort?
Both split the list and sort the parts the same way. Merge sort splits at the middle without looking and does its work when merging; quicksort does its work when splitting, around a pivot, and then has nothing to merge. Merge sort is always n log n and stable but needs extra memory; quicksort works in place and is usually faster, but bad pivots make it n².
What is the most common mistake?
Writing the greater value instead of the smaller one, or taking the right one when the two are equal. Taking the left one on a tie (<=) is what keeps it stable.
How does "What happens next?" work?
It runs merge sort on a new random list and stops five times to ask what comes next: which value goes first in a merge, which pair is compared next, or how the list looks after a merge. Your answers stay in your browser.

More algorithms