Sub topic 1
What Sorting Means: Order, Keys, and In-Place Comparison Sorts
Bubble sort, selection sort, and insertion sort all solve the same problem under the same rules. This chapter states that problem exactly. It covers what "sorted" means, what a key is, what it means for an algorithm to compare elements, and what "in place" promises. Later chapters judge each algorithm against these definitions, so it pays to get them right here.
Prerequisites
This chapter assumes you can already:
- Write loops and conditionals in a language such as Python.
- Read and write list or array elements by index, including swapping two of them.
- Read Big-O notation such as O(n), O(n²), and O(1), and know that it describes growth rate, not exact counts.
You do not need any earlier exposure to sorting algorithms. All examples use Python 3.
The Sorting Problem, Stated Precisely
A sorting algorithm takes a sequence of n elements a[0], a[1], ..., a[n-1] and produces a rearrangement of them, called a permutation, in which each element is less than or equal to the one after it:
a[0] ≤ a[1] ≤ ... ≤ a[n-1]
This order is called nondecreasing order. People often say "ascending", but "nondecreasing" is more precise because it allows equal neighbors.
A correct sort must meet two conditions, and both matter:
- Ordered: every adjacent pair satisfies a[i] ≤ a[i+1].
- Permutation: the output contains exactly the input's elements, each as many times as it appeared.
Many broken sorts pass the first test and fail the second. A function that returns [], or one that overwrites every slot with the minimum, produces ordered output. Neither one has sorted anything. When you test your own implementations in later chapters, check both conditions.
from collections import Counter
def is_ordered(a):
"""True if every adjacent pair is in nondecreasing order."""
return all(a[i] <= a[i + 1] for i in range(len(a) - 1))
def is_permutation_of(result, original):
"""True if result holds exactly the same elements as original."""
return Counter(result) == Counter(original)
def check_sort(sort_fn, data):
original = list(data)
result = sort_fn(list(data))
return is_ordered(result) and is_permutation_of(result, original)
def broken_sort(a):
# Ordered output, but it has lost elements.
return [min(a)] * len(a) if a else []
print(check_sort(sorted, [3, 1, 2, 1])) # True
print(check_sort(broken_sort, [3, 1, 2, 1])) # False
print(is_ordered(broken_sort([3, 1, 2, 1]))) # True: order alone is not enoughWhat "Less Than or Equal" Has to Mean
The definition above uses ≤, so it only makes sense if the elements have a consistent order. Formally, a sort needs a total order. For any elements x, y, and z, that means:
- Totality: x ≤ y or y ≤ x (any two elements can be compared).
- Antisymmetry: if x ≤ y and y ≤ x, then x and y are equal for sorting purposes.
- Transitivity: if x ≤ y and y ≤ z, then x ≤ z.
Integers and strings (compared character by character) satisfy these rules. Some values do not, and an algorithm given them can return output that is not sorted, even though the algorithm itself has no bug.
The best-known case is floating-point NaN ("not a number"). Every comparison involving NaN returns False, so totality breaks.
nan = float("nan")
print(nan < 1.0, nan > 1.0, nan == nan) # False False False
data = [3.0, nan, 1.0, 2.0]
result = sorted(data)
print(result)
# Where nan sits in the input changes the output, and the
# numbers around nan are not guaranteed to come out in order.Keys and Records
Real programs rarely sort bare numbers. They sort records, such as employees, log lines, or orders, by one field or a combination of fields. The value an algorithm compares is called the key. The rest of the record is satellite data that moves along with its key.
In Python you supply the key as a function. The algorithm compares key(x) with key(y) instead of x with y:
employees = [
("Rivera", "eng", 120),
("Chen", "ops", 95),
("Okafor", "eng", 95),
("Banks", "ops", 110),
]
# Key: salary only.
by_salary = sorted(employees, key=lambda e: e[2])
print(by_salary)
# [('Chen', 'ops', 95), ('Okafor', 'eng', 95), ('Banks', 'ops', 110), ('Rivera', 'eng', 120)]
# Key: department, then salary descending (negate the number).
by_dept_then_salary = sorted(employees, key=lambda e: (e[1], -e[2]))
print(by_dept_then_salary)
# [('Rivera', 'eng', 120), ('Okafor', 'eng', 95), ('Banks', 'ops', 110), ('Chen', 'ops', 95)]Sorting by key brings in a subtlety. Two records can have equal keys while being different records. Chen and Okafor both earn 95. The definition of sorting allows either one to come first. Whether an algorithm keeps them in their input order is called stability. Chapter 9 covers stability in full and shows that one of our three algorithms lacks it. For now, keep in mind that "equal keys" and "identical elements" are different things.
A few practical points about keys:
| Concern | What to do |
|---|---|
| Descending order | Use `reverse=True`, or negate a numeric key |
| Several fields | Return a tuple; Python compares tuples left to right |
| Case-insensitive text | Use `key=str.casefold` |
| Expensive key computation | Python's `sorted` computes each key once; a hand-written sort that calls `key()` inside its comparison recomputes it every time |
| Missing values | Map them to a sentinel, for example `(x is None, x)`, so they sort last |
The hand-written sorts in this tutorial compare elements directly with < and >. You can add a key parameter to any of them by replacing a[j] > a[j + 1] with key(a[j]) > key(a[j + 1]).
Comparison Sorts: Learning Order Only by Asking
A comparison sort learns about its input only by asking whether one element is less than another. It never looks at the bits, digits, or characters of a key. All three algorithms in this tutorial are comparison sorts. This makes them general: they work on any type that has a total order, including tuples, strings, and custom objects.
You can watch the questions a comparison sort asks by wrapping each value in an object that counts calls to <:
class Counted:
comparisons = 0
def __init__(self, value):
self.value = value
def __lt__(self, other):
Counted.comparisons += 1
return self.value < other.value
def __repr__(self):
return repr(self.value)
items = [Counted(v) for v in [5, 2, 9, 1, 7, 3]]
result = sorted(items)
print(result) # [1, 2, 3, 5, 7, 9]
print("comparisons:", Counted.comparisons)Because the algorithm can only ask yes-or-no questions, information theory limits how fast it can go. There are n! possible orderings of n distinct elements, and each comparison can at best halve the number still possible. Any comparison sort therefore needs about log₂(n!) ≈ n log₂ n comparisons in the worst case. Bubble, selection, and insertion sort use O(n²) comparisons in the worst case, well above that bound. Chapters 12 and 13 explain why they are still worth knowing.
Non-comparison sorts, such as counting sort and radix sort, read the keys' digits directly. They can beat n log n, but they only work for keys with suitable structure, such as small integers or fixed-length strings. This tutorial does not cover them.
In Place: What It Promises and What It Does Not
An in-place algorithm rearranges the input inside its own storage and uses only O(1) auxiliary space: a fixed number of extra variables such as loop indices and one temporary value, however large n is. All three algorithms in this tutorial are in place. They modify the list you pass in and need only an index or two plus a slot for the element being moved.
Two different meanings of "in place" cause confusion, and Python's own API shows both:
| Call | Mutates the input? | Extra memory used |
|---|---|---|
| `a.sort()` | Yes, and returns `None` | Up to about n/2 element slots (Timsort's merge buffer) |
| `sorted(a)` | No, returns a new list | A full copy of n elements, plus the merge buffer |
| Hand-written bubble, selection, or insertion sort | Yes | O(1) |
list.sort() is in place in the API sense because it mutates the list. It is not in place in the strict algorithmic sense, because it can allocate a temporary buffer. When an analysis says an algorithm "is in place", it means the strict O(1)-space sense.
Mutation also has consequences for the caller:
def insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
original = [4, 1, 3]
alias = original
result = insertion_sort(original)
print(original, alias, result is original) # [1, 3, 4] [1, 3, 4] TrueEvery name that refers to that list now sees the sorted version. The sorts in this tutorial return a for convenience, but the return value is the same object they were given. If the caller needs the original order, the caller must copy first with insertion_sort(list(data)). (Chapter 6 explains how this insertion sort works. Here it only shows the effect of mutation.)
Edge Cases Every Sort Must Handle
Before looking at any algorithm, list the inputs on which it must behave correctly:
- Empty list (n = 0): return immediately. Loops like
range(n - 1)produce no iterations, which is correct, but check any code that readsa[0]. - One element: already sorted.
- All equal keys: no element should move. Moving equal elements wastes writes and can break stability.
- Already sorted and reverse sorted: the extremes. Chapter 8 shows that they are the best and worst cases for some of these algorithms but not for others.
- Many duplicates: a common source of bugs when code uses
<in one place and<=in another.
Exercises
Exercise
A function returns its input list unchanged whenever the list has fewer than 3 elements, and otherwise returns a correctly sorted copy. Which of the two correctness conditions does it violate, and on which input would check_sort catch it?
Show answer
It violates the ordered condition. The permutation condition still holds because no elements are lost. Any 2-element list that is out of order, such as [2, 1], exposes the bug: the function returns [2, 1], so isordered is False and checksort returns False.
Exercise
You want to sort a list of (name, score) tuples by score from highest to lowest, breaking ties by name in alphabetical order. Write the key function, and explain why reverse=True alone does not work.
Show answer
Use key=lambda r: (-r[1], r[0]). Negating the score puts the highest score first, and the name stays in ascending order. With key=lambda r: (r[1], r[0]) and reverse=True, the whole tuple is reversed, so names tied on score would come out in reverse alphabetical order.
Exercise
Is the following statement true or false? "Because Python's list.sort() mutates the list and returns None, it uses O(1) auxiliary space." Explain.
Show answer
False. Mutating the list makes it in place in the API sense only. CPython's list.sort() uses Timsort, which can allocate a temporary merge buffer of up to about n/2 elements, so its auxiliary space is O(n). Bubble, selection, and insertion sort are in place in the strict sense: they use O(1) extra space.
Exercise
Why is a sort of the list [2.0, float('nan'), 1.0] not guaranteed to return [1.0, 2.0, nan] or any other ordered result?
Show answer
Every comparison involving NaN returns False, so NaN is neither less than, greater than, nor equal to any value. The comparison is no longer a total order, and totality and transitivity both fail. A comparison sort relies on those properties to infer order, so its output depends on which pairs it happened to compare and can leave the regular numbers out of order.