Sub topic 5
Best case: the cheapest input
This chapter assumes you can read Python loops, index into lists, and add simple sums like 1 + 2 + ... + n. It also assumes you know that running time is counted as basic operations, written as a function of input size n.
What the best case is
Two inputs of the same size n can make an algorithm do different amounts of work. The best case is the input of size n that makes the algorithm do the least work. Its cost is a function of n, the same kind of function as any other running time.
The best case is a property of the algorithm and a chosen size n. It is not the smallest n. An empty list is a small input, not a best-case input. To find the best case, hold n fixed and ask which arrangement of the data is cheapest.
Best case of linear search
Linear search checks each item in order and stops at the first match. This version counts its comparisons.
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, 7)) # (0, 1)The target 7 is in the first position, so the loop stops after 1 comparison. That count does not depend on n. For every n, the best case of linear search costs 1 comparison.
Best case of insertion sort
Insertion sort takes each element and moves it left past larger elements. On already sorted input, each element is compared once with its left neighbor and stays where it is.
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))) # 5, which is n - 1The outer loop runs for i = 1 to n - 1, which is n - 1 iterations. Each does one comparison, so the best case is n - 1. This cost grows with n, unlike the constant best case of linear search.
Finding a best case in practice
- Fix n.
- Find the input shape that triggers the earliest exit or the least repeated work.
- Count the operations for that shape as a function of n.
- Check the count with a small run, as in the code above.
Why study it
The best case sets a lower limit on the cost for each n. Every input of size n costs at least this much. It also shows what an algorithm is sensitive to. Insertion sort's best case tells you it does well on nearly sorted data, which is a real use. The next chapters compare it with the worst and average cases.
Exercise
A function scans a list of n distinct numbers from the left and returns as soon as it finds a number greater than 100, counting one comparison per element checked. What input of size n gives the best case, and how many comparisons does it cost?
Show answer
The best case is a list whose first element is greater than 100. The scan stops after 1 comparison, for any n.