How do the three foundational O(N^2) sorting algorithms work—and why does Insertion Sort beat complex algorithms on tiny or nearly sorted lists?


In 30 Seconds

Bubble Sort, Selection Sort, and Insertion Sort are the three classic O(N^2) in-place sorting algorithms. Bubble Sort repeatedly swaps adjacent out-of-order neighbors; Selection Sort finds the minimum remaining item and places it in front; Insertion Sort builds a sorted left section one card at a time—running in blazing O(N) best-case time on nearly sorted data.

The Real-World Analogy: Sorting a Hand of Playing Cards

Think of organizing five playing cards dealt to your hand:

  • Insertion Sort: You hold sorted cards in your left hand, pick up each new card, and slide it left into its proper spot.
  • Selection Sort: You scan the entire table for the lowest card, put it first, then scan the remaining cards for the next lowest.
  • Bubble Sort: You compare neighbors side by side, letting the largest card float to the right end like a bubble rising in water.

Picture This

Insertion Sort on [ 7 | 3 | 5 | 2 ]:
Step 1: [ 3, 7 | 5, 2 ]  (3 slides left before 7)
Step 2: [ 3, 5, 7 | 2 ]  (5 slides between 3 and 7)
Step 3: [ 2, 3, 5, 7 ]     (2 slides all the way to index 0!)

Show Me The Code

# Day 15: Bubble, Selection, and Insertion Sort from Scratch in Python

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr


def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr


def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

Speed & Memory

AlgorithmBest CaseAverage CaseWorst CaseSpaceStable?
Insertion SortO(N)O(N^2)O(N^2)O(1)Yes
Selection SortO(N^2)O(N^2)O(N^2)O(1)No
Bubble SortO(N)O(N^2)O(N^2)O(1)Yes

Where You'll See It In Real Life

  • Python's Timsort & C++ Introsort: Production sorting engines switch to Insertion Sort for small subarrays (< 32 items) because its low CPU cache overhead outperforms recursion.
  • Live Leaderboard Updates: Adding one new score to an already-sorted leaderboard takes O(N) with Insertion Sort.

TL;DR

  • Bubble, Selection, and Insertion Sort all sort in-place using O(1) extra memory and O(N^2) average time.
  • Insertion Sort is the fastest of the trio in practice and achieves O(N) on nearly sorted inputs.

References consulted: GeeksforGeeks Sorting Algorithms — referenced for verification — all content above is original.