Measuring Cost Precisely
Complexity analysis determines how an algorithm's resource use — time (operations) and space (memory) — grows with input size , so you can compare algorithms and predict scaling without running them.
The tool is asymptotic notation, which describes growth for large , ignoring constants and lower-order terms:
- Big-O () is an upper bound: the algorithm grows at most this fast.
- Big-Omega () is a lower bound: at least this fast.
- Big-Theta () is a tight bound: both — the algorithm grows exactly this fast.
To analyze, count the dominant operations as a function of : a single loop over the data is ; a loop inside a loop is ; halving each step is ; and constant work regardless of is . Only the fastest-growing term matters: is just , because for large the term dominates.
Costs can differ by case. The worst case (the input that makes the algorithm slowest) is the usual guarantee — it bounds performance no matter what. The average case describes typical behavior over expected inputs (quicksort is average but worst). The best case is often uninformative.
Do not forget space complexity: an algorithm may be fast but memory-hungry. Merge sort is time but needs extra space to merge, while heapsort sorts in place with extra — another space–time trade-off to weigh.
Common pitfall: keeping constant factors and lower-order terms in a Big-O answer, writing "." Asymptotic analysis drops constants and lower-order terms: that is simply . The whole point is to compare growth shape, not exact operation counts — the dominant term alone captures how the algorithm scales.