mid = (left + right) // 2
Middle index in Python binary search
Understand why O(1) hash lookup and O(log n) binary search beat nested O(n²) loops.
Binary search requires a SORTED array and halves the search interval every step, achieving O(log₂ n) time — finding an element in 1,000,000 items takes at most 20 comparisons.
| Complexity | Algorithm / Operation | Steps for n = 1,000 |
|---|---|---|
| O(1) | Hash table / Python dict lookup | 1 |
| O(log n) | Binary search (sorted array) | ~10 |
| O(n) | Linear scan through list | 1,000 |
| O(n log n) | Merge sort / Timsort (sorted()) | ~10,000 |
| O(n²) | Nested loops / Bubble sort | 1,000,000 |
Middle index in Python binary search
Binary search gives wrong answers if order is not monotonic.
What is the average time complexity of looking up a key in a Python dict (hash map)?