Skip to content
Visual explainer 2h to learn 4 steps

Elementary sorts: bubble, selection, insertion

Implement the quadratic sorts and explain stability and when insertion sort wins.

By Invicly Tech, , in Data Structures & Algorithms. About 10 minutes to read.

Topic 20 of 54

In short

Bubble, selection and insertion sort are simple O(n^2) algorithms that sort in place. They are rarely used on large data, but insertion sort is very fast on small or nearly sorted arrays and is used inside hybrid sorts like Timsort. They also introduce stability and in-place sorting.

Explained simply

Sorting means putting items in order, like arranging cards in your hand. The three simplest methods are bubble sort, selection sort and insertion sort. They are easy to understand and use almost no extra memory, but they get slow on big lists.

Bubble sort walks through the list and swaps any two neighbours that are in the wrong order. After one walk, the largest item has bubbled to the end. Repeat until a walk makes no swaps.

Selection sort finds the smallest item and puts it first, then finds the next smallest and puts it second, and so on. Insertion sort works like sorting cards: take the next card and slide it left into its correct place among the cards already sorted.

All three take about n^2 steps for n items in the worst case. With 10 items that is fine. With a million items it is a trillion steps. But insertion sort has a secret strength: on a list that is already almost sorted, it is very fast. That is why real sorting libraries still use it for small pieces.

Press Play on a diagram to walk through it one step at a time.

CompareQuadratic sorts
Bubble
  • Swap adjacent out-of-order pairs
  • O(n^2), O(n) if no swaps
  • Stable
  • Teaching only
Selection
  • Pick the minimum each pass
  • Always O(n^2)
  • Not stable
  • At most n swaps
Insertion
  • Insert each item into sorted prefix
  • O(n^2), O(n) nearly sorted
  • Stable
  • Best for small n
FlowInsertion sort on [4, 2, 5, 1]
  1. 1
    Start

    Sorted prefix [4], rest [2, 5, 1].

  2. 2
    Insert 2

    Shift 4 right: [2, 4, 5, 1]. 1 shift.

  3. 3
    Insert 5

    No shift: [2, 4, 5, 1].

  4. 4
    Insert 1

    Shift 5, 4, 2: [1, 2, 4, 5]. 3 shifts.

  5. 5
    Done

    4 shifts = 4 inversions in the input.

In depth

Counting the work exactly

Bubble sort compares neighbours. Pass k compares n - k pairs, so a full run is (n - 1) + (n - 2) + ... + 1 = n(n - 1)/2 comparisons. With an early-exit flag, it stops after the first pass with no swaps, so sorted input takes only n - 1 comparisons.

Selection sort always makes n(n - 1)/2 comparisons, even on sorted input, because it must scan the rest of the list to be sure it has the minimum. But it makes at most n - 1 swaps, the fewest of the three. That helps only when writing to memory is very expensive.

Insertion sort's cost depends on the input. Each shift fixes exactly one inversion (a pair in the wrong order), so the number of shifts equals the number of inversions. That is 0 for sorted input, n(n - 1)/2 for reversed input, and n(n - 1)/4 on average for random input.

  • Bubble: n(n-1)/2 comparisons, n - 1 with early exit on sorted input
  • Selection: always n(n-1)/2 comparisons, at most n - 1 swaps
  • Insertion: shifts = inversions

Stability: why it matters

A sort is stable if items that compare equal keep their original order. Suppose you have orders already sorted by time, and you sort them by customer. A stable sort keeps each customer's orders in time order. An unstable sort may shuffle them.

Insertion sort is stable because it shifts an item left only past strictly greater items (a[j] > key). Change that to >= and equal items jump over each other, breaking stability. Bubble sort is stable for the same reason: it swaps only when the left item is strictly greater.

Selection sort is not stable in its usual form. Sorting [(2, 'a'), (2, 'b'), (1, 'c')] by the number, the first pass swaps (1, 'c') with (2, 'a'), giving [(1, 'c'), (2, 'b'), (2, 'a')]: the two 2s have changed order. A stable version shifts items instead of swapping, but then it does more writes.

FlowSelection sort breaking stability
  1. 1
    Start

    [2a, 2b, 1c]

  2. 2
    Find min

    1c is the minimum.

  3. 3
    Swap with first

    [1c, 2b, 2a]: 2a jumped over 2b.

  4. 4
    Pass 2

    2b is the minimum of the rest: no change.

  5. 5
    Result

    Sorted, but 2b now comes before 2a.

Why insertion sort wins on nearly sorted data

Insertion sort runs in O(n + I) time, where I is the number of inversions. If every item is at most k positions from its final place, each item shifts at most k times, so the total is O(n k). For k = 3 that is linear time.

Real data is often like this: a log file that is mostly in timestamp order, a leaderboard where only a few scores changed, or a list where new items were appended to an already sorted list.

Insertion sort is also fast on tiny arrays (say under 32 to 64 items) because its inner loop is simple and touches neighbouring memory. Fancy O(n log n) sorts have higher constant costs. So hybrid sorts split the work: Timsort, used by Python, extends short natural runs to a minimum length (between 32 and 64) using binary insertion sort, then merges the runs.

  • Time O(n + inversions)
  • Items at most k away from home: O(nk)
  • Small inputs: lowest overhead of any sort

In-place, online and adaptive

Three more words help describe sorts. In-place means only O(1) extra memory is used besides the input. All three elementary sorts are in-place.

Online means the algorithm can sort items as they arrive, without seeing the whole input first. Insertion sort is online: each new item is inserted into the already sorted prefix. Python's bisect.insort does the same for a list, with O(log n) comparisons to find the spot but O(n) time to shift items.

Adaptive means the algorithm runs faster when the input is already partly sorted. Insertion sort and bubble sort with early exit are adaptive. Selection sort is not: it does the same comparisons regardless of input.

Binary insertion sort uses binary search to find where to insert, cutting comparisons to O(n log n), but shifts remain O(n^2) in the worst case.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Implement bubble and selection sort~30m
  2. 2
    Implement insertion sort~30m
  3. 3
    Define stable and in-place sorting~30m
  4. 4
    Explain insertion sort on nearly sorted data~30m

Key points

  • All three use O(1) extra space.
  • Insertion sort's cost is O(n + inversions).
  • Stable sorts keep equal keys in their original order.
  • Timsort uses insertion sort on short runs.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def insertion_sort(a):            # O(n^2) worst, O(n) nearly sorted
    for i in range(1, len(a)):
        key, j = a[i], i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
    return a

print(insertion_sort([5, 2, 4, 6, 1, 3]))

Counting operations on sorted, reversed and random input

We instrument insertion sort to count shifts and compare three inputs of 1,000 items. Sorted input needs 0 shifts. Reversed input needs 1000 * 999 / 2 = 499,500 shifts. Random input lands near the average of n(n - 1)/4, about 250,000. The same algorithm differs by a factor of hundreds of thousands depending on the data.

python
import random

def insertion_shifts(a):
    a, shifts = a[:], 0
    for i in range(1, len(a)):
        key, j = a[i], i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]; j -= 1; shifts += 1
        a[j + 1] = key
    return shifts

n = 1000
print(insertion_shifts(list(range(n))))         # 0
print(insertion_shifts(list(range(n, 0, -1))))  # 499500
print(insertion_shifts(random.sample(range(n), n)))  # about 250000

Bubble and selection sort side by side

Bubble sort with a swapped flag stops early when a pass makes no swaps. Selection sort finds the index of the minimum in the unsorted part and does one swap per pass. On [5, 1, 4, 2, 8], bubble sort needs 3 passes (the third has no swaps), while selection sort always does 4 passes, comparing every remaining item each time.

python
def bubble_sort(a):
    for end in range(len(a) - 1, 0, -1):
        swapped = False
        for i in range(end):
            if a[i] > a[i + 1]:
                a[i], a[i + 1] = a[i + 1], a[i]; swapped = True
        if not swapped: break
    return a

def selection_sort(a):
    for i in range(len(a) - 1):
        m = min(range(i, len(a)), key=a.__getitem__)
        a[i], a[m] = a[m], a[i]
    return a

print(bubble_sort([5, 1, 4, 2, 8]), selection_sort([5, 1, 4, 2, 8]))

Quick reference

  • Bubble: O(n^2), O(n) on sorted input with early exit, stable, in-place
  • Selection: always n(n-1)/2 comparisons, at most n - 1 swaps, not stable
  • Insertion: O(n + inversions), stable, in-place, online, adaptive
  • Average inversions in a random permutation: n(n-1)/4
  • Keep stability: shift or swap only on strictly greater (>), never >=
  • Timsort uses binary insertion sort to build runs of 32 to 64 items
  • bisect.insort keeps a list sorted: O(log n) search, O(n) insert

Common mistakes

  • Using > versus >= carelessly, which breaks stability.
  • Choosing a quadratic sort for large inputs.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1How many comparisons does selection sort make on an already sorted list of 10 items?

Question 2

2An array has 12 inversions. How many shifts will insertion sort perform?

Question 3

3Which change makes insertion sort unstable?

Question 4

4Why does Python's Timsort use insertion sort at all?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write count_inversions_slow(a) that counts pairs i < j with a[i] > a[j] using two loops. Check that it matches the number of shifts insertion sort makes on [4, 2, 5, 1].

  2. Exercise 2medium

    Write a stable insertion sort that sorts a list of (name, age) tuples by age only. Example: [('a', 30), ('b', 25), ('c', 30)] gives [('b', 25), ('a', 30), ('c', 30)].

  3. Exercise 3hard

    Each item in a list is at most k positions away from its sorted position. Sort it in O(n log k) using a heap, and explain why insertion sort would be O(nk). Example: ([3, 1, 2, 6, 4, 5], k=2) gives [1, 2, 3, 4, 5, 6].

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is bubble sort ever used in real code?
Almost never. Insertion sort does the same job with fewer writes and better speed, so bubble sort survives mainly as a teaching tool.
Which simple sort should I learn first?
Insertion sort. It is stable, adaptive, used inside real library sorts, and the shifting loop teaches the invariant of a sorted prefix.
Why is selection sort not stable if it only swaps?
A long-distance swap can move an element past another equal element. For example, swapping the first of two equal items to the far end reverses their order.

Go deeper

ShareXLinkedInWhatsApp