The same algorithm can behave differently on different inputs. The best case is the cheapest input, the worst case is the most expensive, and the average case is the expected cost over typical inputs. Guarantees are usually stated for the worst case. For linear search on n items: best 1 comparison, worst n, average about (n + 1) / 2 for present keys.
Remember
best : key is first -> 1 comparison
worst : key last or absent -> n comparisons
average : key anywhere -> about (n + 1) / 2
Reference
Cheat Sheet
Keep these facts handy while you work with Best, Average and Worst Case Analysis in C in C.
Seven values; try first, middle, and missing keys.
C
#include <stdio.h>
static int comparisons(const int a[], int n, int key) {
int c = 0;
for (int i = 0; i < n; i++) {
c++;
if (a[i] == key) break;
}
return c;
}
int main(void) {
int a[] = {5, 3, 8, 1, 9, 2, 7};
int n = 7, total = 0;
printf("key 5: %d comparison (best)\n", comparisons(a, n, 5));
printf("key 1: %d comparisons\n", comparisons(a, n, 1));
printf("key 4: %d comparisons (worst, absent)\n", comparisons(a, n, 4));
for (int i = 0; i < n; i++) total += comparisons(a, n, a[i]);
printf("average over present keys: %.1f\n", (double)total / n);
return 0;
}
Output
key 5: 1 comparison (best)
key 1: 4 comparisons
key 4: 7 comparisons (worst, absent)
average over present keys: 4.0
How It Works
Key 5 is first, so one comparison suffices.
Key 1 is at index 3, which costs four comparisons.
The average of 1 through 7 is 28 / 7 = 4.0, which matches (n + 1) / 2.
Edge Cases & Pitfalls
Check these before relying on Best, Average and Worst Case Analysis in C in real programs.
best
Advertising the best case
A best case rarely represents real inputs. Quote the worst case for guarantees.
avg
Average depends on assumptions
State the input distribution when you quote an average.
Remember
Key Takeaways
Same algorithm, different inputs.
Worst case is the guarantee.
Average needs assumptions.
One line: The same algorithm can behave differently on different inputs.
Frequently Asked Questions
They are the minimum, expected, and maximum cost of an algorithm over inputs of the same size.
The worst case, because it provides a guarantee for any input.
Continue with "Comparing Algorithms in C" next. Compare two correct solutions by counting operations. The C Algorithm Basics hub lists every topic in order.