Bubble, Selection and Insertion Sort in Python
Bubble sort, selection sort and insertion sort are the first sorting algorithms most people learn. All three are O(n^2) in the worst case and sort in place with O(1) extra space, so they look interchangeable on paper. They are not: on sorted input, on nearly sorted input and in the number of writes they make, they behave very differently, and one of them, insertion sort, is still used inside production sorting routines. Examples use Python 3.10 or later and only the standard library.
The three algorithms
Bubble sort
Walk through the list comparing neighbors and swap any pair that is out of order. After one pass, the largest item has "bubbled" to the end; after the second pass, the second largest is in place; and so on. Each pass can stop one position earlier than the last. The important detail is the swapped flag: if a whole pass makes no swaps, the list is sorted and the algorithm can stop.
Selection sort
Find the smallest item in the unsorted part and swap it to the front of that part. Repeat with the next position. The sorted part grows by one item per pass, and every pass scans the whole unsorted part to find its minimum.
Insertion sort
Treat the first item as a sorted list of one. Take the next item and shift the larger items of the sorted part one place right until there is a gap where it belongs, then drop it in. This is how many people sort a hand of playing cards.
def bubble_sort(a):
a = list(a)
n = len(a)
for end in range(n - 1, 0, -1): # after each pass, a[end] is final
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: # no swaps: already sorted, stop
break
return a
def selection_sort(a):
a = list(a)
n = len(a)
for i in range(n - 1):
smallest = i
for j in range(i + 1, n): # find the minimum of a[i:]
if a[j] < a[smallest]:
smallest = j
a[i], a[smallest] = a[smallest], a[i] # one swap per pass
return a
def insertion_sort(a):
a = list(a)
for i in range(1, len(a)):
x = a[i] # the item to insert
j = i - 1
while j >= 0 and a[j] > x: # shift larger items right
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
return a
data = [5, 2, 9, 1, 5, 6]
print(bubble_sort(data))
print(selection_sort(data))
print(insertion_sort(data))
[1, 2, 5, 5, 6, 9]
[1, 2, 5, 5, 6, 9]
[1, 2, 5, 5, 6, 9]
Each function copies its input with list(a) so the examples do not modify data; a real in-place sort would work on the caller's list directly.
Insertion sort, step by step
Here is insertion sort on a five-item list, printing the list after each item is inserted:
a = [4, 1, 5, 3, 2]
print("start ", a)
for i in range(1, len(a)):
x = a[i]
j = i - 1
while j >= 0 and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
print(f"insert {x}", a, " sorted part:", a[:i + 1])
start [4, 1, 5, 3, 2]
insert 1 [1, 4, 5, 3, 2] sorted part: [1, 4]
insert 5 [1, 4, 5, 3, 2] sorted part: [1, 4, 5]
insert 3 [1, 3, 4, 5, 2] sorted part: [1, 3, 4, 5]
insert 2 [1, 2, 3, 4, 5] sorted part: [1, 2, 3, 4, 5]
Inserting 1 shifts 4 right. Inserting 5 shifts nothing, because 5 is already larger than everything before it: one comparison and done. Inserting 3 shifts 5 and 4. Inserting 2 shifts 5, 4 and 3. The number of shifts equals the number of pairs that were out of order (called inversions), which is the key to insertion sort's behavior.
Counting comparisons on three kinds of input
The table of complexities is easier to believe when you count. This program counts comparisons (and selection sort's swaps) for 100 items that are already sorted, shuffled with a fixed seed, and reversed:
import random
def bubble(a):
a, comps = list(a), 0
for end in range(len(a) - 1, 0, -1):
swapped = False
for i in range(end):
comps += 1
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
if not swapped:
break
return comps
def selection(a):
a, comps, swaps = list(a), 0, 0
for i in range(len(a) - 1):
m = i
for j in range(i + 1, len(a)):
comps += 1
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
swaps += 1
return comps, swaps
def insertion(a):
a, comps = list(a), 0
for i in range(1, len(a)):
x, j = a[i], i - 1
while j >= 0:
comps += 1
if a[j] <= x:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
return comps
n = 100
random.seed(2026)
inputs = {"sorted": list(range(n)),
"random": random.sample(range(n), n),
"reversed": list(range(n, 0, -1))}
print(f"n = {n}, n*(n-1)/2 = {n * (n - 1) // 2}")
print(f"{'input':9} {'bubble':>7} {'selection':>10} {'(swaps)':>8} {'insertion':>10}")
for name, a in inputs.items():
c, s = selection(a)
print(f"{name:9} {bubble(a):7} {c:10} {s:8} {insertion(a):10}")
n = 100, n*(n-1)/2 = 4950
input bubble selection (swaps) insertion
sorted 99 4950 0 99
random 4935 4950 97 2536
reversed 4950 4950 50 4950
Reading the output:
- Bubble sort makes 99 comparisons on sorted input, one pass with no swaps, thanks to the early exit. That is its O(n) best case. On random and reversed input it does almost all n(n - 1)/2 = 4,950 comparisons: O(n^2). Without the
swappedflag it would make 4,950 comparisons even on sorted input. - Selection sort makes exactly 4,950 comparisons on every input, because finding a minimum always means scanning the whole unsorted part. It is O(n^2) in the best, average and worst case. Its strength is the swap count: at most n - 1 swaps (97 on the random input, 50 on the reversed one, where each swap fixes two items), compared with up to one swap per comparison for bubble sort.
- Insertion sort makes 99 comparisons on sorted input (O(n)), about n^2/4 on random input (2,536 here), and 4,950 on reversed input (O(n^2), every item shifts all the way to the front). In general its work is about n plus the number of inversions, so on nearly sorted input, where each item is a few places from home, it runs in close to linear time.
Stability
A stable sort keeps items with equal keys in their original relative order, which matters when you sort records by one field after another (see sorting algorithms compared for a worked example).
- Bubble sort is stable, as long as it swaps only when
a[i] > a[i + 1]. Swapping on>=would move equal items past each other. - Insertion sort is stable for the same reason: the inner loop shifts only items strictly greater than
x, soxstops behind any equal item. - Selection sort is not stable in its usual form. The swap that brings the minimum forward can throw the item it displaces far down the list, past an equal item. For example, with records keyed B, B, A, the first pass swaps A with the first B, which ends up behind the second B.
Summary
| Algorithm | Best | Average | Worst | Swaps or writes | Stable |
|---|---|---|---|---|---|
| Bubble sort | O(n), with the early exit | O(n^2) | O(n^2) | Up to n(n - 1)/2 swaps | Yes |
| Selection sort | O(n^2) | O(n^2) | O(n^2) | At most n - 1 swaps | No |
| Insertion sort | O(n), sorted input | O(n^2) | O(n^2) | One shift per inversion | Yes |
All three use O(1) extra space. The Algorithm Comparison Tool includes bubble sort (O(n) best, which assumes the early-exit check, and O(n^2) average and worst, O(1) space, stable) and lets you see how far it falls behind the O(n log n) sorts as n grows: at n = 1000 its average-case count is 1,000,000 against 9,965.78 for merge sort. The tool's counts are values of the growth functions, not timings.
When to use them
For general sorting, use Python's built-in sorted(), which is O(n log n) in the worst case. The simple sorts still matter for three reasons:
- Insertion sort is fast on small or nearly sorted inputs. Its inner loop is tiny and it does almost no work when items are close to their final place. That is why hybrid sorts, which use merge sort or quicksort for the big picture, commonly switch to insertion sort for small pieces.
- Selection sort minimizes writes. When writing an item is much more expensive than comparing two, its n - 1 swaps can matter.
- They teach the ideas that later sorts build on: in-place swapping, loop invariants (after pass i, the first i items are sorted), stability, and best case versus worst case. Bubble sort is the weakest of the three in practice and is mostly a teaching example.
The O(n log n) sorts that replace them for large inputs are explained in merge sort and quicksort.
Check yourself
- How many comparisons does bubble sort with the early exit make on a sorted list of 1,000 items? (999.)
- Why does selection sort make 4,950 comparisons on sorted input of 100 items? (It must scan the whole unsorted part to be sure it found the minimum.)
- A list of 10,000 items is sorted except that two neighbors are swapped. Which simple sort handles it fastest, and roughly how many comparisons does it make? (Insertion sort, about 10,000: one inversion to fix.)