Cases are different claims
Best case, worst case, and average case are three separate statements. Naming one is not claiming another.
Plan against the worst
Design uses the worst case. A fast average can still hide a slow input that matters.
The same algorithm can cost different amounts depending on the input. Naming which case you mean keeps the claim honest.
About 2 min of reading
Name the best, worst, and average case of a scan.
Target first.
Before you run it, say out loud what it will print. Then open the answer.
Target last.
Before you run it, say out loud what it will print. Then open the answer.
Sorted pass, no swaps.
Before you run it, say out loud what it will print. Then open the answer.
Reverse needs swaps.
Before you run it, say out loud what it will print. Then open the answer.
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
Best case, worst case, and average case are three separate statements. Naming one is not claiming another.
Design uses the worst case. A fast average can still hide a slow input that matters.
a = [7, 2, 5]
target = 7
steps = 0
for x in a:
steps += 1
if x == target:
break
print(steps)
The target is first, so the scan stops after one step. That is the best case.
a = [7, 2, 5]
target = 5
steps = 0
for x in a:
steps += 1
if x == target:
break
print(steps)
The target is last, so the scan uses all n steps. That is the worst case.
a = [1, 2, 3]
swaps = 0
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
swaps += 1
print(swaps)
A pass over sorted data makes no swaps. Bubble sort best case is one pass.
a = [3, 2, 1]
swaps = 0
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
swaps += 1
print(swaps)
Reversed data needs the most swaps. That is the worst case for the same code.
a = [4, 1, 3, 2]
target = 3
steps = 0
for x in a:
steps += 1
if x == target:
break
print(steps)
A random target sits in the middle on average, so about n over two steps. Same class as n.
print("best 1, worst n, average n over 2")
A claim without a case is vague. Best, worst, and average are different promises.
n = 1000
print("worst", n, "best", 1)
Systems are planned against the worst case. A lucky best case is not a plan.
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.