The same algorithm can be fast on one input and slow on another. Searching a list is instant if the item is first, and slow if it is missing. Best, average and worst case analysis puts a number on each of those situations, so you know what to expect before you run the code.
In this lesson you will learn
- What best, average and worst case mean, with numbers you can measure
- How linear search and insertion sort behave in each case
- Which algorithms have the same cost on every input
- Which case to quote, and why worst case is the usual choice
- Why “best case” is not the same thing as Big Omega
Three Questions About One Algorithm
For an input of size n, we can ask three different questions:
| Case | Question | How often it is used |
|---|---|---|
| Worst case | Which input of size n makes the algorithm do the most work? | Most common. It is a guarantee: the algorithm is never slower than this. |
| Average case | If inputs arrive at random, how much work do we expect? | Useful in practice, but needs an assumption about what “random” means. |
| Best case | Which input of size n makes it do the least work? | Rarely quoted on its own, because it is usually a lucky special case. |
Linear Search: Counting Comparisons
Linear search checks items one by one until it finds the target. The program below counts how many comparisons it makes for three different targets in an 8-item list.
#include <stdio.h>
/* Linear search that also reports how many comparisons it made. */
static int search(const int a[], int n, int target, int *comparisons) {
*comparisons = 0;
for (int i = 0; i < n; i++) {
(*comparisons)++;
if (a[i] == target) return i;
}
return -1;
}
int main(void) {
int roll_numbers[] = {11, 24, 7, 39, 15, 52, 3, 46};
int n = 8, cmp, pos;
pos = search(roll_numbers, n, 11, &cmp);
printf("best case (first item) : index %2d, %d comparisons\n", pos, cmp);
pos = search(roll_numbers, n, 39, &cmp);
printf("middle item : index %2d, %d comparisons\n", pos, cmp);
pos = search(roll_numbers, n, 99, &cmp);
printf("worst case (not present) : index %2d, %d comparisons\n", pos, cmp);
return 0;
}
Output
best case (first item) : index 0, 1 comparisons
middle item : index 3, 4 comparisons
worst case (not present) : index -1, 8 comparisons
- Best case: the target is the first item. One comparison, whatever n is: O(1).
- Worst case: the target is missing (or last). Every item is checked: n comparisons, O(n).
- Average case: if the target is present and equally likely to be at any position, the search stops halfway on average, about n/2 comparisons. Dropping the constant gives O(n).
Average and worst case have the same growth rate here. The average saves half the work, but it still grows in a straight line with n.
Insertion Sort: Input Order Changes Everything
Insertion sort takes each item and slides it left until it reaches its place. How far each item slides depends on how mixed-up the input is. Here it sorts three 1,000-item arrays.
#include <stdio.h>
/* Insertion sort that counts comparisons between elements. */
static long insertion_sort(int a[], int n) {
long comparisons = 0;
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0) {
comparisons++;
if (a[j] <= key) break;
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
return comparisons;
}
int main(void) {
enum { N = 1000 };
static int sorted[N], reversed[N], mixed[N];
unsigned seed = 12345;
for (int i = 0; i < N; i++) {
sorted[i] = i;
reversed[i] = N - i;
seed = seed * 1103515245u + 12345u; /* simple fixed pseudo-random */
mixed[i] = (int)((seed >> 16) % 10000);
}
printf("n = %d\n", N);
printf("already sorted : %7ld comparisons\n", insertion_sort(sorted, N));
printf("random order : %7ld comparisons\n", insertion_sort(mixed, N));
printf("reverse sorted : %7ld comparisons\n", insertion_sort(reversed, N));
return 0;
}
Output
n = 1000
already sorted : 999 comparisons
random order : 259261 comparisons
reverse sorted : 499500 comparisons
- Already sorted: every item is already in place, so each needs one comparison. That is n − 1 = 999 comparisons, O(n).
- Reverse sorted: every item slides all the way to the front. That is 1 + 2 + … + (n − 1) = n(n − 1)/2 = 499,500 comparisons, O(n²).
- Random order: each item slides about halfway, roughly n²/4 comparisons. The run shows 259,261, close to 1,000²/4 = 250,000. Still O(n²).
This is why insertion sort is a good choice for data that is almost sorted, and a poor choice for random data.
Cases for Common Algorithms
| Algorithm | Best | Average | Worst | Worst-case input |
|---|---|---|---|---|
| Linear search | O(1) | O(n) | O(n) | Target missing |
| Binary search (sorted array) | O(1) | O(log n) | O(log n) | Target missing |
| Insertion sort | O(n) | O(n²) | O(n²) | Reverse sorted |
| Bubble sort (with early stop) | O(n) | O(n²) | O(n²) | Reverse sorted |
| Quick sort | O(n log n) | O(n log n) | O(n²) | Bad pivots every time, such as a sorted array with first-element pivot |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | None: same on every input |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | None: same on every input |
| Hash table lookup | O(1) | O(1) | O(n) | Every key lands in the same bucket |
Merge sort always splits the array in half and always merges every item, so its work does not depend on the order of the data. Quick sort is usually faster in practice, but its worst case is much worse. That trade-off is why many libraries pick pivots randomly or switch algorithms when recursion gets too deep.
Which Case Should You Quote?
- Quote the worst case by default. It is a promise that holds for every input, which is what you need for deadlines, servers and safety-critical code.
- Add the average case when it is very different and inputs really are random, as with quick sort or hash tables.
- Mention the best case only when it is useful, such as “insertion sort is O(n) on nearly sorted data”.
Cases are not the same as O, Ω and Θ
A common mix-up is “worst case = Big O, best case = Big Omega”. That is wrong. O, Ω and Θ describe bounds on a function. Best, worst and average case decide which function you are bounding. For example, insertion sort’s worst case is Θ(n²): it is both O(n²) and Ω(n²). See Big O, Omega and Theta notation.
Common Mistakes
- Quoting the best case as the speed of an algorithm. “Linear search is O(1)” is true only when the item happens to be first.
- Choosing the best case by shrinking n. The best case is the cheapest input of size n, not “when n = 1”.
- Assuming random input when it is not. Real data is often partly sorted, which hurts a naive quick sort and helps insertion sort.
- Testing only one kind of input. Always try sorted, reverse-sorted and random data when you measure a sort.
- Treating O(n/2) as different from O(n). Constants are dropped; both are O(n).
Practice Exercises
Exercise 1. Binary search on a sorted array of 1,024 items. How many comparisons in the best case, and roughly how many in the worst case?
Show answer
Best case: 1 (the middle item is the target). Worst case: about log₂1024 + 1 = 11.
Exercise 2. A function returns early if the array’s first element is negative; otherwise it loops over all n items. Give its best and worst case.
Show answer
Best case O(1) (first element negative); worst case O(n).
Exercise 3. How many comparisons does the insertion sort above make on a reverse-sorted array of 100 items?
Show answer
100 × 99 / 2 = 4,950.
Frequently Asked Questions
Why is worst-case analysis used most often?
Because it is a guarantee. Whatever input arrives, the algorithm will not be slower than its worst case, which lets you plan time limits and server capacity.
Is average case always between best and worst case?
Yes. An average of costs can never be below the smallest cost or above the largest one.
Is best case the same as Big Omega?
No. Big Omega is a lower bound on a function. You can give an Omega bound for the worst case, the best case or the average case.
How do I find the worst-case input?
Ask what makes the algorithm keep going as long as possible: a missing search target, a reverse-sorted array for insertion sort, or bad pivots for quick sort.
Summary
- Best, average and worst case measure the same algorithm on its cheapest, typical and most expensive inputs of size n.
- Linear search: O(1) best, O(n) average and worst.
- Insertion sort: O(n) on sorted data, O(n²) on random or reversed data.
- Merge sort and heap sort cost O(n log n) on every input.
- Quote the worst case by default; add the average case when it differs a lot.
