When to use sorting and binary search
Sort when you need:
- Data in order for display, such as a leaderboard, a price list or search results.
- Equal items next to each other, to remove duplicates, count groups or compare two lists.
- To prepare for something faster: binary search, two pointers or merging all want sorted input.
Use binary search when:
- You have sorted data and will search it more than once.
- You want a position, not just yes or no: the first item at least
x, the last item at mostx, or where to insertx. - You have a yes or no question that flips once, such as "does this version work?", and want the first "yes". This is binary search on the answer.
Use something else when:
- You search once in unsorted data: a plain scan is O(n), cheaper than sorting first at O(n log n).
- You look up exact keys all the time: use a hash map.
- The data changes constantly and must stay sorted: use a balanced tree.
- You only need the smallest or largest few items: use a heap.
- The keys are small whole numbers: counting sort can beat any comparison sort.
Do not write your own sort in production. Every language ships a tuned one, and a binary search is in the standard library of most (see the real-world section). Writing them by hand is for learning and interviews.
How sorting and binary search work
Binary search finds a value in a sorted list by looking at the middle first.
If the middle item is too small, everything to its left is too small as well, so discard that whole half. If it is too big, discard the right half. Repeat on what is left.
Each look throws away half of the remaining items, so 1,000 items need at most about 10 looks and a million need about 20. That is O(log n). It only works because the list is sorted.
Sorting puts items in order. Two classic methods that both beat the simple O(n²) ones:
- Merge sort splits the list in half, sorts each half, then merges the two sorted halves by repeatedly taking the smaller front item. It always takes O(n log n) time, needs O(n) extra memory for the merging, and is stable (equal items keep their original order).
- Quick sort picks a pivot, moves smaller items to its left and larger ones to its right, then sorts each side the same way. It is O(n log n) on average and sorts in place, but if the pivot keeps being the smallest or largest item, it falls to O(n²).
Binary search on the answer uses the same halving on a range of possible answers instead of a list. If you can test "is x big enough?" and the answer flips from no to yes just once as x grows, you can find the smallest x that works in O(log range) tests.
Try it
Pick binary search, merge sort or quick sort and step through. Watch the counters.
Sorting and binary search
Step 1 of 4 · Press Space to play, arrow keys to stepSearch for 23 in the sorted list. Look at the middle item: each look will discard half of what is left.
- comparisons:
- 0
- linear scan would need:
- 10
comparisons = times two values were compared. writes = times a value was written into the array.
Things to try:
- Binary search for
23in the sorted list. It takes 3 comparisons, where scanning from the left needs 6. Then search for40, which is not in the list: it takes 4 comparisons to be sure. - Merge sort with Shuffled: 14 comparisons. With Already sorted: 11. It barely cares about the starting order.
- Quick sort with Shuffled: 11 comparisons. With Already sorted: 21, the worst case for a last-item pivot, which is 7 × 6 ÷ 2. Quick sort is only fast when the pivot splits the data roughly in half.
Sorting and binary search operations
Binary search. Keep low and high. Look at mid. If it is the target, stop. If it is too small, set low to mid + 1. If it is too big, set high to mid - 1. If low passes high, the target is not there.
Merge two sorted halves. Keep one pointer in each half. Compare the two front items, copy the smaller into the result, and move that pointer. When one half runs out, copy the rest of the other.
Partition (quick sort). Choose a pivot. Scan through, moving each item smaller than the pivot to the left region. Put the pivot between the regions. It is now in its final position.
Binary search on the answer. Decide the range of possible answers. Write a function that says yes or no for one candidate. Search for the first yes.
Three bugs to avoid: use mid = low + (high - low) / 2 so the sum cannot overflow, decide whether the loop is low <= high or low < high and keep your updates consistent with it, and make sure each step really shrinks the range, or the loop never ends.
Interview fact. Comparison-based sorting cannot be faster than O(n log n) in the worst case. Binary search is O(log n), but only on sorted data, so sorting first adds O(n log n).
Sorting and binary search time complexity
| Algorithm | Best | Typical | Worst | Extra memory |
|---|---|---|---|---|
| Binary search (loop version) | O(1) | O(log n) | O(log n) | O(1) |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) stack |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) |
| Insertion, bubble and selection sort | O(n) or O(n²) | O(n²) | O(n²) | O(1) |
Stable sorts keep equal items in their original order: merge sort is stable, quick sort and heap sort are not (in their usual forms). Stability matters when you sort by one field and then by another.
Sorting and binary search vs other approaches
The right choice depends on what you do most. n is the number of items and k is the number of results returned.
| What you need | Sorted array + binary search | Unsorted scan | Hash map | Balanced tree |
|---|---|---|---|---|
| Find a value | O(log n) | O(n) | O(1) average | O(log n) |
| Insert a new value | O(n) | O(1) at the end | O(1) average | O(log n) |
| Range query ("between a and b") | O(log n + k) | O(n) | O(n) | O(log n + k) |
| Nearest value (floor or ceiling) | O(log n) | O(n) | O(n) | O(log n) |
| Set-up cost | O(n log n) to sort once | None | O(n) | O(n log n) |
| Memory | O(n), compact | O(n), compact | O(n) plus spare slots | O(n) plus pointers |
The bold cells show where each wins. A sorted array with binary search is the best for data that is built once and queried many times. It is the worst when you insert often, because each insert shifts the items after it.
How to explain sorting and binary search in an interview
- Say the precondition: "binary search needs sorted data, or a yes or no test that flips once."
- Give the cost: "O(log n) per search, and O(n log n) to sort first, so it pays off over many searches."
- Compare sorts in one line: "merge sort is always O(n log n) but uses O(n) memory, quick sort is O(n log n) on average, O(n²) in the worst case, and sorts in place."
- Mention stable when the question sorts by more than one field.
- Name how you avoid off-by-one mistakes: the loop condition, the way
midis computed, and that every step shrinks the range.