Merge sort

Split in half and merge in order · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Merge sort

Merge sort uses divide and conquer in 2 phases. Divide: the array is split in half, and each half again, until all pieces have 1 element. Merge: 2 sorted pieces are joined into a bigger sorted one, and so on until the whole array is done. Since a 1-element piece is already sorted, each merge always joins 2 sorted lists.

Merging is the heart of merge sort. You have 2 sorted lists and a pointer at the start of each. You compare what the 2 pointers point to, copy the smaller one to the result list and move that pointer forward. When one list runs out, whatever's left of the other is copied. Merging 2 lists of total length n costs O(n): each element is looked at once.

Splitting in half gives about log n levels, and at each level the merges walk all n elements: always O(n log n), whatever the data's order. It isn't adaptive. The recursion uses O(log n) stack, but merging needs an auxiliary array: O(n) extra memory, so it isn't in place. And it's stable: when merging, if 2 are equal, the one from the left list goes first.

Merge sort has a special advantage with linked lists: it can sort them with O(1) extra memory. Splitting can be done with a loop, without recursion. And merging 2 linked lists only changes references, without creating a new list or copying anything. That's why it's the preferred sort for linked lists.

Merge sort and quick sort are both O(n log n) on average, but each wins at something. Merge sort guarantees O(n log n) always and is stable, in exchange for O(n) memory. Quick sort is in place and faster in practice, in exchange for an O(n²) worst case and not being stable. Many languages use merge sort variants when they need stability, like for sorting objects.

Stable sort

Merge sort is stable because, when merging 2 lists, if the 2 compared elements are equal, it copies the one from the left list first. Since the left list comes from the earlier part of the array, the original order among equal values is kept. It's one of its big advantages over quick sort and heap sort.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Split in half and merge in order