Algorithms and complexity · Part 14 of 36
Sorting algorithms step by step
Intermediate 18 min
Insertion, selection, merge and quick sort compared: how they work, what they cost and what "stable" means.
What you will learn
- You can describe insertion, selection, merge and quick sort.
- You can state their time complexity and whether they are stable.
- You can use your language’s built-in sort with a key or compare function.
Before this: Big-O: how cost grows with input
Why study sorting?
You will rarely write a sort function yourself — every language has a fast, tested one. But sorting is the best playground for algorithm ideas: incremental building, divide and conquer, randomisation and the limits of what's possible.

Insertion sort — O(n²)
Take items one by one and insert each into its place in the already-sorted part on the left, shifting bigger items right. It is how many people sort playing cards. Worst case n(n − 1)/2 comparisons, but on almost-sorted data it is nearly O(n), and it is stable: equal items keep their original order.
Selection sort — O(n²)
Find the smallest item, swap it to the front, repeat with the rest. Always n(n − 1)/2 comparisons, but only n − 1 swaps — useful only when writing is very expensive. Not stable.
Merge sort — O(n log n)
Divide and conquer: split the list in halves, sort each half (recursively), then merge the two sorted halves by repeatedly taking the smaller front item. There are log₂ n levels of splitting and each level merges n items: O(n log n) in every case. Stable, but needs O(n) extra memory.
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:]
Quick sort — O(n log n) on average
Pick a pivot, partition the items into "smaller" and "bigger", then sort both parts recursively. With good pivots the parts halve and the cost is O(n log n); with consistently bad pivots (e.g. always the first item of already sorted data) it degrades to O(n²). Random or median-of-three pivots make that practically impossible. It sorts in place and is very fast in practice, but it is not stable.
The limit: n log n
Any sort that only compares pairs needs at least about log₂(n!) ≈ n log₂ n comparisons in the worst case — there are n! possible orders and each comparison can at most halve them. So merge sort is optimal among comparison sorts. Algorithms that don't compare, such as counting or radix sort, can beat it for special data like small integers.
Built-in sorts
- Python:
sorted(items, key=lambda p: p["kg"], reverse=True)— stable; it uses Timsort and, since Python 3.11, the Powersort merge policy. - JavaScript:
items.sort((a, b) => a.kg - b.kg)— stable since ECMAScript 2019; it sorts in place.toSorted()(ES2023) returns a sorted copy.
Stability lets you sort by several keys: sort by name first, then by bed — items in the same bed stay alphabetical.
Try it: Sorting step by step
Watch five sorting algorithms compare and move items, and count their comparisons and writes.
Turn on JavaScript to use this lab. Worked example:
The lab shows each step: bars being compared are highlighted, and counters show comparisons and writes. For 10 items merge sort needs between 15 and 25 comparisons, insertion sort up to 45.
Key points
- Insertion sort: O(n²), stable, fast on nearly sorted data.
- Selection sort: O(n²) comparisons, few swaps, not stable.
- Merge sort: O(n log n) always, stable, O(n) extra memory.
- Quick sort: O(n log n) average, O(n²) worst, in place, not stable.
- Comparison sorting can't beat about n log₂ n comparisons; use the built-in stable sorts with key/compare functions.
Flashcards
- Question: What does "stable sort" mean?
- Answer: Equal items keep their original relative order.
- Question: What is merge sort's time complexity?
- Answer: O(n log n) in every case.
- Question: When does quick sort degrade to O(n²)?
- Answer: When pivots repeatedly split the data very unevenly (e.g. first item on sorted data).
- Question: Which JavaScript method returns a sorted copy?
- Answer: toSorted() (ES2023).
Check yourself
Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.
Match the algorithm with its worst-case time.
Show the answer
Insertion sort = O(n²); Merge sort = O(n log n); Binary search (not a sort) = O(log n)
Merge sort is O(n log n) in every case; insertion sort is quadratic in the worst case.
Source: CLRS ch. 2
How many comparisons does insertion sort need in the worst case for 6 items?
Show the answer
15
n(n − 1)/2 = 6 × 5 / 2 = 15.
Source: CLRS 2.2
Which sorts are stable in their usual form?
- Merge sort
- Insertion sort
- Quick sort
- Selection sort
Show the answer
Merge sort; Insertion sort
Merge and insertion sort keep equal items in order; standard quick and selection sort do not.
Source: CLRS ch. 2, 7
Why does a merge sort of n items have about log₂ n levels?
- Each level halves the size of the pieces
- Each level removes one item
- Each level sorts one item
- It compares every pair
Show the answer
Each level halves the size of the pieces
Splitting in halves reaches pieces of size 1 after log₂ n levels.
Source: MIT 6.006, Lecture 3
Sources
- Introduction to Algorithms (4th ed.), Cormen, Leiserson, Rivest & Stein, MIT Press, 2022
- MIT OpenCourseWare 6.006 Introduction to Algorithms, Demaine, Ku & Solomon, 2020
- Python documentation: Sorting Techniques, Python Software Foundation, 2025
Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.