Sub topic 1
What Sorting Means: Order, Keys, and In-Place Comparison Sorts
Prerequisites
This chapter assumes you can write loops and conditionals, index into Python lists, and read Big-O notation such as O(n) and O(n²).
The Sorting Problem
Sorting takes a sequence and rearranges it so each element is less than or equal to the next. The value you compare is the key. It can be the whole element or one field of a record, such as the age in a (age, name) tuple.
All three algorithms in this tutorial are comparison sorts: they learn about the order only by asking whether a[x] > a[y]. They are also in-place: they rearrange the input list using O(1) extra memory instead of building a new list.
Counting the Work
Big-O alone hides differences that matter here, so we count these operations separately:
| Measure | Meaning |
|---|---|
| Comparisons | Key tests such as `a[j] > a[j + 1]` |
| Swaps | Exchanging two elements, which costs two writes |
| Shifts | Copying one element one slot over, which costs one write |
| Auxiliary space | Memory used beyond the input |
Two sorts can have the same O(n²) comparison count and still differ a lot in how many writes they make.
Bubble Sort
Bubble sort walks the list and swaps each adjacent pair that is out of order. Each pass carries the largest remaining value to the end, where it stays. After pass i, the last i + 1 positions hold their final values, so the inner loop can stop before reaching them.
Stopping Early
If a pass makes no swaps, every adjacent pair is already in order, so the whole list is sorted. A swapped flag lets the sort stop at that point. On sorted input, this cuts the cost to a single pass: n − 1 comparisons, O(n).
def bubble_sort(a):
n = len(a)
for i in range(n - 1):
swapped = False
# After pass i, the last i + 1 positions hold their final values.
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
print(bubble_sort([5, 1, 4, 2, 8])) # [1, 2, 4, 5, 8]In the worst case, reverse-sorted input, bubble sort makes n(n − 1)/2 comparisons and the same number of swaps.
Exercise
How many comparisons and swaps does the early-exit bubble sort make on [1, 2, 3, 4, 5], and on [5, 4, 3, 2, 1]?
Show answer
On [1, 2, 3, 4, 5] it makes 4 comparisons and 0 swaps, then stops after one pass. On [5, 4, 3, 2, 1] it makes 4 + 3 + 2 + 1 = 10 comparisons and 10 swaps.