Sub topic 6
Worst Case: The Most Expensive Input
This chapter assumes you can read Python loops, index lists, and sum series such as 1 + 2 + ... + n. It also assumes you know that running time is counted in basic operations as a function of input size n.
What the worst case is
For a fixed input size n, different inputs can cost different amounts. The worst case is the largest cost over all inputs of size n. It is a function of n. It is not a single input and not a single number.
Written as a formula, with T(x) as the cost on input x:
W(n) = max of T(x) over all inputs x of size n
To derive W(n), do two things. First, show that no input of size n costs more than some count. Second, exhibit one input that reaches that count.
Linear search
Linear search compares the target to each item in turn and stops at a match. The loop body runs at most once per item, so no input costs more than n comparisons. Two kinds of input reach n: the target is in the last position, or the target is absent. So W(n) = n.
def linear_search(items, target):
comparisons = 0
for i, x in enumerate(items):
comparisons += 1
if x == target:
return i, comparisons
return -1, comparisons
items = [7, 3, 9, 1, 5]
print(linear_search(items, 5)) # last position: 5 comparisons
print(linear_search(items, 42)) # absent: 5 comparisonsInsertion sort
For insertion sort, the key at position i is compared against the sorted items to its left. It can be compared with at most i of them, so the total is at most 1 + 2 + ... + (n - 1) = n(n - 1)/2. Reverse-sorted input with distinct values reaches that bound, because every key moves all the way to the front.
def insertion_sort_comparisons(values):
a = list(values)
comparisons = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] > key:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = key
return comparisons
n = 6
print(insertion_sort_comparisons(range(n, 0, -1))) # 15 = n(n-1)/2Common errors
- Stopping after step one. An upper bound that no input reaches is not the worst case.
- Choosing an input that merely looks bad. Check it against the count. For insertion sort, an input in which every item is out of place may still not be reverse sorted.
- Mixing input sizes. The worst case compares inputs of the same n only.
Exercise
Linear search runs on a list of 8 distinct items. What is the worst-case number of comparisons? Name two inputs that reach it.
Show answer
The worst case is 8 comparisons. Two inputs that reach it are a target in the last position and a target that is absent from the list.
Exercise
What is the worst-case number of comparisons for insertion sort when n = 10, and which input produces it?
Show answer
n(n - 1)/2 = 10 × 9 / 2 = 45 comparisons. The input is a list of 10 distinct values in reverse sorted order.