Measuring scalability
Big O describes how a resource requirement grows with input size, usually considering worst-case growth for a stated algorithm. It does not give exact elapsed seconds.
| Complexity | Example |
|---|---|
| O(1) | Reading an array item by index |
| O(log n) | Binary search in a sorted array |
| O(n) | Linear search |
| O(n log n) | Efficient comparison sorts such as merge sort |
| O(n²) | Simple nested-loop pair comparisons |
Analyse this code
def count_matches(a):
matches = 0
for x in a:
for y in a:
if x == y:
matches += 1
return matchesFor n values, how many comparisons occur? Identify the time complexity and discuss the space complexity excluding the input.
Suggested answer
n² comparisons, O(n²) time and O(1) auxiliary space.
