Big O and operation counts
Count inner work before simplifying the expression. These examples count all unordered index pairs.
| Scan | Θ(n) | One item per iteration |
| Halving | Θ(log n) | Remaining work drops by a constant factor |
| All pairs | Θ(n²) | n(n−1)/2 distinct index pairs |
| Balanced merge sort | Θ(n log n) | Linear merge work over logarithmically many levels |
Python
def pair_count(n):
count = 0
for i in range(n):
for j in range(i + 1, n):
count += 1
return countC++
long long pairCount(int n) {
long long count = 0;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) ++count;
return count;
}Java
static long pairCount(int n) {
long count = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) count++;
return count;
}