Sorting and Searching Algorithms Questions
Comparison and non-comparison sorting (quicksort with its pivot and partition choices and hybrid cutoffs, mergesort, heapsort as a sort, insertion/selection/bubble, counting/radix/bucket), their stability, in-place behavior, stack depth and lower bounds, and choosing a sort from input constraints, including near-sorted data, library sorts (Timsort, introsort, language defaults), comparator design and expensive comparisons or copies. Also selection (quickselect, median-of-medians, nth_element), external merge sorting of data larger than memory (run generation and merge passes), and binary search with its variants: first/last occurrence, lower/upper bound, rotated arrays with or without duplicates, peak and mountain arrays, sorted matrices, unbounded search, loop-invariant correctness and off-by-one pitfalls, and binary search on an answer space (discrete or continuous, including k-th smallest by value). Includes divide-and-conquer reasoning for sorts (merge step, merging sorted arrays, median of two sorted arrays, inversion counting). Excludes heap data-structure mechanics and heap-based top-k and k-way merging, trees and tries, general graph search, distributed data-processing systems, approximate nearest-neighbor and streaming-sketch algorithms, and abstract Big-O comparison.
Implement selection sort in C++ to sort an array of integers in place. Do not use library sort functions. Provide complexity analysis and explain one scenario where selection sort might be preferable despite O(n^2) time.
Sample Answer
Direct answer
Selection sort splits the array into a sorted prefix (at the front) and an unsorted rest. On each pass it scans the unsorted rest to find the smallest value, then swaps it into the first unsorted slot. It runs in O(n^2) time (always exactly n(n-1)/2 comparisons), uses O(1) extra space, and performs at most n-1 swaps. That small, bounded number of writes is the one scenario where it can beat the other quadratic sorts: when writing to the array is far more expensive than reading it (for example flash memory, a kind of storage whose cells wear out after a limited number of rewrites, or records that are large to move).
The idea in plain words
Imagine laying cards face up and repeatedly picking the smallest remaining card to place next in a new row. Selection sort does the same inside the array, so it needs no second row. The invariant (a statement that is true before and after every pass) is: after pass i, positions 0 to i hold the i+1 smallest values, in sorted order, and they never move again.
Terms used below: in place means the sort needs only a constant amount of extra memory besides the array. Stable means that items with equal keys keep their original relative order.
Approach
- For i from 0 to n-2: assume the minimum of a[i..n-1] is at index i.
- Scan j from i+1 to n-1; whenever a[j] is smaller than the current minimum, remember j.
- If the remembered index is not i, swap a[i] with it.
- The last element needs no pass: once n-1 values are in place, the final one must be the largest.
The algorithm on its own
This is the whole sort, for int values, with nothing else around it:
#include <iostream>
#include <utility>
#include <vector>
void selection_sort(std::vector<int>& a) {
for (std::size_t i = 0; i + 1 < a.size(); ++i) { // i is the first slot not yet sorted
std::size_t min_index = i; // where the smallest value seen so far sits
for (std::size_t j = i + 1; j < a.size(); ++j)
if (a[j] < a[min_index]) min_index = j;
std::swap(a[i], a[min_index]); // put that smallest value into slot i
}
}
int main() {
std::vector<int> a = {29, 10, 14, 37, 13};
selection_sort(a);
for (int x : a) std::cout << x << ' ';
std::cout << '\n';
}
Compiled the same way as the program further down (g++ -std=c++17 -O2 -Wall), it prints:
10 13 14 29 37
Line by line: the outer loop picks the slot i that is about to receive the next smallest value. min_index starts as i itself. The inner loop looks at every later slot j and moves min_index whenever it finds something smaller. After the inner loop, std::swap exchanges slot i with the smallest value found. The outer loop stops at i + 1 < a.size() because the last slot is correct once all earlier ones are.
Code
The program below wraps those same few lines in scaffolding so it can count work and test several element types. The sorting loop in it is the one above, plus counters and a skipped swap when the minimum is already in place; everything else is for measuring and checking:
template <typename T, typename Less>makes one function work for any element typeTand any comparison functionLess, so the same code sortsintvalues andTaggedrecords.[](int x, int y) { return x < y; }is a lambda, an inline function with no name; it is passed in asless, the rule for "comes before".Statsholds three counters (comparisons, swaps, array writes) that the sort increments as it works.if constexpr (std::is_arithmetic_v<T>)is a check done when the program is compiled: the trace line is printed only whenTis a number type, because aTaggedrecord has no<<printing.std::mt19937 rng(42)is a random number generator with a fixed seed, so the shuffled test arrays are the same on every run.
selection_sort is a template so the same function sorts integers and tagged records. It returns counts of comparisons, swaps and array-slot writes, taken from the function that does the sorting. insertion_sort appears only to compare the number of writes. The driver prints the array after every pass, runs the edge cases, tests stability with tagged equal keys, and checks 500 random arrays with many duplicates against std::sort.
#include <algorithm>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <random>
#include <type_traits>
#include <vector>
struct Stats {
long comparisons = 0;
long swaps = 0;
long writes = 0; // array slots assigned
};
// In-place selection sort. After pass i, a[0..i] holds the i+1 smallest values in order.
template <typename T, typename Less>
Stats selection_sort(std::vector<T>& a, Less less, bool trace = false) { // trace needs T printable
Stats s;
const std::size_t n = a.size();
for (std::size_t i = 0; i + 1 < n; ++i) {
std::size_t min_index = i;
for (std::size_t j = i + 1; j < n; ++j) {
++s.comparisons;
if (less(a[j], a[min_index])) min_index = j;
}
if (min_index != i) { // skip the swap when the minimum is already in place
std::swap(a[i], a[min_index]);
++s.swaps;
s.writes += 2;
}
if constexpr (std::is_arithmetic_v<T>) if (trace) {
std::cout << "after pass " << i + 1 << " (picked index " << min_index << "): ";
for (const T& x : a) std::cout << x << ' ';
std::cout << '\n';
}
}
return s;
}
// Insertion sort, shipped only to compare the number of array writes.
template <typename T, typename Less>
Stats insertion_sort(std::vector<T>& a, Less less) {
Stats s;
for (std::size_t i = 1; i < a.size(); ++i) {
T key = a[i];
std::size_t j = i;
while (j > 0) {
++s.comparisons;
if (!less(key, a[j - 1])) break;
a[j] = a[j - 1];
++s.writes;
--j;
}
a[j] = key;
++s.writes;
}
return s;
}
struct Tagged {
int key;
char tag;
};
int main() {
auto int_less = [](int x, int y) { return x < y; };
std::vector<int> demo = {29, 10, 14, 37, 13};
std::cout << "start: 29 10 14 37 13\n";
Stats s = selection_sort(demo, int_less, true);
std::cout << "comparisons=" << s.comparisons << " swaps=" << s.swaps << "\n\n";
// Edge cases
std::vector<int> empty, one = {7}, equal = {5, 5, 5}, sorted = {1, 2, 3, 4};
for (auto* v : {&empty, &one, &equal, &sorted}) {
Stats e = selection_sort(*v, int_less);
std::cout << "size " << v->size() << ": comparisons=" << e.comparisons
<< " swaps=" << e.swaps << '\n';
}
// Stability test with tagged equal keys: 3a, 3b, 1c -> a stable sort gives 1c 3a 3b
std::vector<Tagged> t = {{3, 'a'}, {3, 'b'}, {1, 'c'}};
selection_sort(t, [](const Tagged& x, const Tagged& y) { return x.key < y.key; });
std::cout << "\ntagged result: ";
for (auto& x : t) std::cout << x.key << x.tag << ' ';
std::cout << " (stable would be 1c 3a 3b)\n";
// Counts for n = 8 and n = 16 on one fixed random permutation each, plus the write comparison
std::mt19937 rng(42);
std::cout << "\n n selection(cmp,swaps,writes) insertion(cmp,writes) n(n-1)/2 n-1\n";
for (std::size_t n : {8, 16, 32, 64}) {
std::vector<int> base(n);
for (std::size_t i = 0; i < n; ++i) base[i] = static_cast<int>(i);
std::shuffle(base.begin(), base.end(), rng);
std::vector<int> a = base, b = base, ref = base;
Stats sa = selection_sort(a, int_less);
Stats sb = insertion_sort(b, int_less);
std::sort(ref.begin(), ref.end());
if (a != ref || b != ref) { std::cout << "MISMATCH\n"; return 1; }
std::cout << std::setw(3) << n << " " << sa.comparisons << "," << sa.swaps << "," << sa.writes
<< " | " << sb.comparisons << "," << sb.writes << " | "
<< n * (n - 1) / 2 << " " << n - 1 << '\n';
}
// Randomised check against std::sort, with duplicates
std::uniform_int_distribution<int> val(0, 9), len(0, 12);
for (int trial = 0; trial < 500; ++trial) {
std::vector<int> v(len(rng));
for (auto& x : v) x = val(rng);
std::vector<int> ref = v;
std::sort(ref.begin(), ref.end());
selection_sort(v, int_less);
if (v != ref) { std::cout << "FAIL\n"; return 1; }
}
std::cout << "500 random arrays with duplicates match std::sort\n";
return 0;
}
Compiled with g++ 14.2 (g++ -std=c++17 -O2 -Wall), it prints:
start: 29 10 14 37 13
after pass 1 (picked index 1): 10 29 14 37 13
after pass 2 (picked index 4): 10 13 14 37 29
after pass 3 (picked index 2): 10 13 14 37 29
after pass 4 (picked index 4): 10 13 14 29 37
comparisons=10 swaps=3
size 0: comparisons=0 swaps=0
size 1: comparisons=0 swaps=0
size 3: comparisons=3 swaps=0
size 4: comparisons=6 swaps=0
tagged result: 1c 3b 3a (stable would be 1c 3a 3b)
n selection(cmp,swaps,writes) insertion(cmp,writes) n(n-1)/2 n-1
8 28,5,10 | 23,24 | 28 7
16 120,12,24 | 92,95 | 120 15
32 496,29,58 | 278,282 | 496 31
64 2016,58,116 | 1117,1119 | 2016 63
500 random arrays with duplicates match std::sort
Reading the trace
Starting from 29 10 14 37 13:
- Pass 1 scans four candidates, finds 10 at index 1, swaps it with the 29 at index 0.
- Pass 2 finds 13 at index 4 and swaps it into index 1.
- Pass 3 finds that 14 is already at index 2, so no swap happens (this is the
min_index != icheck). - Pass 4 compares 37 with 29, finds 29 at index 4 and swaps.
Comparisons: 4 + 3 + 2 + 1 = 10. Swaps: 3, fewer than the maximum n-1 = 4 because pass 3 needed none.
Complexity, with the reason
- Time: the inner loop runs n-1, n-2, ..., 1 times, so comparisons are always n(n-1)/2 whatever the input. The table confirms it: 28, 120, 496 and 2016 for n = 8, 16, 32 and 64, on random permutations. Doubling n roughly quadruples the comparisons. Even an already sorted array costs the full count (the
size 4row shows 6 comparisons, no swaps), so there is no early exit and no best case better than O(n^2). - Swaps and writes: at most one swap per pass, so at most n-1 swaps and 2(n-1) slot writes. The table shows 116 writes for n = 64, against 1119 for insertion sort on the same permutation.
- Space: O(1): two indices and a swap temporary, and no recursion.
Edge cases and common mistakes
- Empty and one-element arrays: the outer loop
i + 1 < nnever runs (the size 0 and size 1 rows show 0 comparisons). Writing the bound asi < n - 1with an unsignednunderflows whennis 0 in C++, which is why the code usesi + 1 < n. - All-equal input: strict
<means the minimum index never moves, so no swaps happen (the size 3 row). - Duplicates in general: handled, as the 500 random arrays over only ten distinct values show.
- The sort is not stable. The tagged test sorted
3a 3b 1cinto1c 3b 3a: the first swap moved 1c to the front by exchanging it with 3a, and 3a jumped past 3b. Making it stable means shifting elements instead of swapping, which costs O(n) writes per pass and removes the property that makes the sort attractive. - Mistakes to avoid: swapping inside the inner loop every time a smaller value is seen (that makes O(n^2) swaps, which is bubble-sort-like behaviour), and storing the minimum value but not its index.
When selection sort is the right choice despite O(n^2)
Pick it when writes are the scarce resource and the array is small enough that quadratic reads are acceptable. Examples: sorting records stored in flash or EEPROM (a small rewritable memory chip common in embedded devices) where every write wears the cell, or sorting a few dozen large structs whose move costs far more than a comparison. It does at most n-1 swaps, where insertion sort did 1119 writes and selection 116 at n = 64. For large n, or when stability matters, prefer merge sort or a library sort, which are O(n log n).
Explain how the binary search algorithm works on a sorted array. Describe required preconditions, the standard iterative implementation steps, the loop invariants you would maintain, and its time and space complexity. Give two concrete examples of problems where binary search is appropriate and two where it is not, and explain why.
Sample Answer
Direct answer
Big-O notation says how the work grows with the number of items n: O(n) is proportional to n, O(log n) grows by one step each time n doubles, and O(1) is a fixed amount. Binary search finds a target in a sorted array by repeatedly looking at the middle element and throwing away the half that cannot contain the target. Each step halves the remaining window, so it takes O(log n) comparisons and O(1) extra space in its iterative form. It needs two preconditions: the data is sorted by the same ordering the comparison uses, and you can jump to any position in O(1) time (random access).
The idea in plain words
Think of guessing a number from 1 to 1000 when each answer is "higher" or "lower". Guess 500; if told "higher", you now know the number is in 501 to 1000 and never look at 1 to 500 again. Each guess removes half of what is left, so ten guesses are enough (2^10 = 1024). A sorted array gives exactly this: if the middle value is smaller than the target, then everything to its left is smaller too (that is what "sorted ascending" means), so the target cannot be there.
Preconditions
- The array is sorted in ascending order (or the comparison is flipped for descending). If it is not sorted, "everything to the left is smaller" is false and discarding half is wrong.
- Random access in O(1): the array must let you read
arr[mid]directly. A linked list does not. - Comparisons are consistent: the same ordering that sorted the data decides "less than" during the search. Sorting strings case-insensitively and searching case-sensitively breaks it.
- Duplicates are allowed, but then the plain version returns any matching index, not necessarily the first or last one.
Iterative implementation, step by step
- Keep a window
arr[lo..hi], both ends inclusive, starting as the whole array:lo = 0,hi = n - 1. - While the window is not empty (
lo <= hi), computemid = lo + (hi - lo) // 2. - If
arr[mid]equals the target, returnmid. - If
arr[mid]is smaller than the target, the target can only be to the right: setlo = mid + 1. Otherwise sethi = mid - 1. - When the loop ends, the window is empty, so return -1.
The loop invariant (a statement that is true before and after every iteration, which is what proves the loop correct): if the target is anywhere in the array, it is inside arr[lo..hi]. It holds at the start because the window is the whole array. Each update keeps it true because only positions that are provably too small (lo = mid + 1) or too big (hi = mid - 1) are dropped, and mid itself is excluded because it was just checked. It also guarantees the loop ends, because the window shrinks by at least one element each round. When the loop stops with lo > hi, the window is empty, and since the target would have to be inside it, the target is absent.
Writing mid = lo + (hi - lo) // 2 rather than (lo + hi) // 2 matters in languages with fixed-width integers: in a 32-bit signed int, lo + hi can exceed 2,147,483,647 once the array has more than 2^30 (1,073,741,824) elements, and in Java it then wraps to a negative number: with lo = 1_100_000_000 and hi = 1_200_000_000, (lo + hi) / 2 is -997,483,648 while lo + (hi - lo) / 2 is 1,150,000,000. In C and C++ the signed overflow is undefined behaviour. Python integers never overflow, so either form works there, but the safe form is the habit to keep.
Code
The function returns the index and the number of comparisons it made, and the driver prints lo, hi and mid at every step.
from typing import List, Tuple
def binary_search(arr: List[int], target: int, trace: bool = False) -> Tuple[int, int]:
"""Return (index or -1, number of comparisons with target).
Invariant: if target is in arr at all, it is inside arr[lo..hi] (inclusive).
"""
lo, hi = 0, len(arr) - 1
comparisons = 0
while lo <= hi:
mid = lo + (hi - lo) // 2
comparisons += 1
if trace:
print(f" lo={lo} hi={hi} mid={mid} arr[mid]={arr[mid]}")
if arr[mid] == target:
return mid, comparisons
if arr[mid] < target:
lo = mid + 1 # everything at or left of mid is too small
else:
hi = mid - 1 # everything at or right of mid is too big
return -1, comparisons # lo > hi: the window is empty, so target is absent
if __name__ == "__main__":
arr = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print("search 23 in", arr)
print(" result:", binary_search(arr, 23, trace=True))
print("search 40 (absent):")
print(" result:", binary_search(arr, 40, trace=True))
cases = [
("empty", [], 5),
("one element, hit", [7], 7),
("one element, miss", [7], 3),
("all equal, hit", [4, 4, 4, 4], 4),
("target absent", arr, 40),
("target at left end", arr, 2),
("target at right end", arr, 91),
("smaller than all", arr, -1),
("larger than all", arr, 1000),
]
print("\nedge cases")
for name, data, t in cases:
idx, c = binary_search(data, t)
ok = (data[idx] == t) if idx != -1 else (t not in data)
assert ok
print(f" {name:20s} -> index {idx}, comparisons {c}")
print("\nworst-case comparisons (target absent, larger than all)")
for n in (10, 1000, 1_000_000):
_, c = binary_search(list(range(n)), n + 5)
print(f" n={n:>9,}: {c} comparisons")
Run in a python:3.12 container, it prints:
search 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
lo=0 hi=9 mid=4 arr[mid]=16
lo=5 hi=9 mid=7 arr[mid]=56
lo=5 hi=6 mid=5 arr[mid]=23
result: (5, 3)
search 40 (absent):
lo=0 hi=9 mid=4 arr[mid]=16
lo=5 hi=9 mid=7 arr[mid]=56
lo=5 hi=6 mid=5 arr[mid]=23
lo=6 hi=6 mid=6 arr[mid]=38
result: (-1, 4)
edge cases
empty -> index -1, comparisons 0
one element, hit -> index 0, comparisons 1
one element, miss -> index -1, comparisons 1
all equal, hit -> index 1, comparisons 1
target absent -> index -1, comparisons 4
target at left end -> index 0, comparisons 3
target at right end -> index 9, comparisons 4
smaller than all -> index -1, comparisons 3
larger than all -> index -1, comparisons 4
worst-case comparisons (target absent, larger than all)
n= 10: 4 comparisons
n= 1,000: 10 comparisons
n=1,000,000: 20 comparisons
Worked trace
Searching for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]: the window starts as positions 0 to 9, mid is 4 and arr[4] is 16, which is smaller than 23, so lo becomes 5. The window 5 to 9 gives mid 7 and arr[7] is 56, larger, so hi becomes 6. The window 5 to 6 gives mid 5 and arr[5] is 23, a match: index 5 after 3 comparisons. Searching for the absent 40 follows the same first three steps, then the window shrinks to position 6 (value 38, smaller than 40), lo becomes 7 which is past hi = 6, and the function returns -1 after 4 comparisons.
Complexity
Time is O(log n): each round halves the window, so at most floor(log2 n) + 1 rounds are needed. The run shows 4 comparisons for n = 10, 10 for n = 1,000 and 20 for n = 1,000,000 in the worst case (target larger than everything), which matches that formula. Space is O(1): three integers and a counter. A recursive version would use O(log n) stack. The cost of sorting first, O(n log n), is only worth paying when many searches follow.
The mistakes listed at the end can be tried directly. The function below is the same search with one mistake switched on at a time, and gives up after 50 rounds so that a stuck loop shows up as loops; it runs on every array of 1, 2 and 3 elements (values 0 to n - 1) with every target from -1 to n.
def variant(arr, target, mistake=None, limit=50):
lo, hi = 0, len(arr) - 1
for _ in range(limit):
if (lo >= hi) if mistake == "lo < hi" else (lo > hi):
return -1
mid = lo + (hi - lo) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
lo = mid if mistake == "lo = mid" else mid + 1
else:
hi = mid if mistake == "hi = mid" else mid - 1
return "loops"
for mistake in (None, "lo < hi", "lo = mid", "hi = mid"):
bad = []
for n in (1, 2, 3):
data = list(range(n))
for target in range(-1, n + 1):
expected = target if 0 <= target < n else -1
got = variant(data, target, mistake)
if got != expected:
bad.append(f"n={n} target={target} -> {got}")
print(f"{str(mistake):9s}", bad if bad else "all correct")
Output (python:3.12):
None all correct
lo < hi ['n=1 target=0 -> -1', 'n=2 target=1 -> -1', 'n=3 target=0 -> -1', 'n=3 target=2 -> -1']
lo = mid ['n=1 target=1 -> loops', 'n=2 target=1 -> loops', 'n=2 target=2 -> loops', 'n=3 target=2 -> loops', 'n=3 target=3 -> loops']
hi = mid ['n=1 target=-1 -> loops', 'n=2 target=-1 -> loops', 'n=3 target=-1 -> loops']
Two problems where binary search fits
- Looking up an ID or timestamp in sorted data. A log file or table sorted by timestamp, searched for the first entry at or after a time: the order exists and positions are directly reachable, so 20 comparisons cover a million records. The same idea works on an answer space: to find the smallest speed at which a task finishes within a deadline, "finishes in time" is false below some speed and true above it, so you can binary search the speed values without any array. Both ideas run on small data below.
- Finding the first bad commit or build. If every commit after a certain one is bad and every commit before it is good, the sequence good...good, bad...bad is ordered by the property being tested, and testing the middle commit halves the range (this is how
git bisect, the Git command that finds the commit that introduced a bug, narrows down a regression). Testing is expensive, so using only about log2(n) tests instead of n matters a lot.
from bisect import bisect_left
# 1. First entry at or after a time, in a log sorted by timestamp (seconds since midnight).
stamps = [100, 160, 160, 250, 400, 900]
want = 200
i = bisect_left(stamps, want)
print(f"first entry at or after {want}: index {i}, timestamp {stamps[i]}")
# 2. Binary search on an answer space: smallest speed so that all piles are finished within 8 hours.
piles = [3, 6, 7, 11] # units of work; at speed s a pile takes ceil(pile / s) hours
deadline = 8
def hours(s):
return sum(-(-p // s) for p in piles)
lo, hi = 1, max(piles) # the answer is somewhere in 1..11; no array exists
while lo < hi:
mid = (lo + hi) // 2
ok = hours(mid) <= deadline
print(f"speed {mid:2d}: {hours(mid):2d} hours -> {'fast enough' if ok else 'too slow'}")
if ok:
hi = mid
else:
lo = mid + 1
print("smallest speed that finishes within", deadline, "hours:", lo)
Output (python:3.12):
first entry at or after 200: index 3, timestamp 250
speed 6: 6 hours -> fast enough
speed 3: 10 hours -> too slow
speed 5: 8 hours -> fast enough
speed 4: 8 hours -> fast enough
smallest speed that finishes within 8 hours: 4
The first part uses the library's bisect_left, which returns the first index whose value is at least the wanted time (the plain version above can only report an exact match, so it cannot answer "first at or after"). The second part never touches an array: the candidate speeds 1 to 11 act as the sorted range, "fast enough" is false below 4 and true from 4 up, and each probe (6, 3, 5, 4) halves the range until it is a single speed.
Two problems where it does not fit
- Unsorted data, such as a list of order IDs in arrival order. Learning that
arr[mid]is smaller than the target says nothing about the left half, because the left half is in no particular order, so you cannot discard anything. Use a linear scan (O(n)), or build a hash set (a structure that answers "is this value present?" in constant time on average) or dictionary once and get O(1) average lookups. Sorting first costs O(n log n), which only helps if you search many times. - A sorted singly linked list. The data is ordered, but there is no O(1) way to reach the middle: walking to
midcosts O(n) every round. The total becomes O(n) in pointer steps, no better than a plain scan, so the logarithmic advantage disappears. A skip list (a linked list with extra layers of forward links that skip over many nodes) or a balanced tree (a search tree whose height stays about log n) restores it, because they add the shortcuts a list lacks.
Edge cases and common mistakes
The run covers an empty array (0 comparisons, -1), one element (hit and miss), all-equal values (returns an index of a match, here 1, not the first), absent targets, targets at both ends, and values smaller or larger than everything.
- Using
lo < hiinstead oflo <= hiskips the last one-element window and misses targets such as the sole element or the last candidate (thelo < hirow of the mistakes run). - Setting
lo = midorhi = midinstead ofmid + 1/mid - 1can loop forever. The window of one element is already enough:midequalsloand the update leaves the window unchanged. Withlo = mida window of two elements sticks too (thelo = midandhi = midrows of the mistakes run). - Computing
(lo + hi) / 2with overflow in fixed-width integers, shown above. - Running it on unsorted data and trusting the answer; there is no error, just wrong output.
- Expecting the first or last duplicate from the plain version.
Running the code
python:3.12, standard library only.
Save the listing as binary_search.py and run: python binary_search.py
Implement an in-place quicksort with a randomized pivot. Keep the recursion depth bounded even on adversarial input, and explain the expected and worst-case running time.
Sample Answer
The idea in plain words
Quicksort picks one element as the pivot, rearranges the list so everything on the left of a split point is no bigger than everything on the right, then sorts each side the same way. It is in-place because it only swaps elements inside the given list; the only extra memory is the call stack.
Two things decide whether it behaves:
- Which pivot. If the pivot is always the first or last element, a sorted list splits into "1 element" and "everything else" every time, which costs about n^2 / 2 comparisons and n nested calls. A pivot chosen uniformly at random from the current range has no input it is reliably bad on, because the adversary (someone who picks the input after studying the pivot rule, to make it slow) cannot predict which element will be picked.
- Which side you recurse into. Recurse into the smaller side and loop on the larger one. Each recursive call then gets at most half the elements, so the stack depth is at most floor(log2 n) + 1 whatever the splits are. With 8 elements the recursive call gets at most 4, then at most 2, then at most 1, so at most log2 8 + 1 = 4 frames are ever stacked; the larger side never adds a frame because the loop reuses the current one. That is the tail-call elimination (turning the last recursive call into a loop) done by hand, because CPython does not do it for you.
Why the simple version is not enough
The textbook version uses the first element as the pivot and recurses on both sides. Run on already-sorted input or on all-equal input of 5000 values it dies with RecursionError (CPython allows about 1000 nested calls by default); the last two lines of the output below show it. A randomized pivot fixes the running time on average, and the smaller-side rule fixes the stack depth even when the random draws are unlucky.
The approach
- Pivot rule shipped: a uniformly random index in
[lo, hi], swapped to positionlo. - Partition scheme: Hoare partition. Two indices start outside the range and walk inward. The left one stops at an element that is not smaller than the pivot, the right one at an element that is not larger; if they have not crossed, those two elements are swapped. When they cross, the right index
jis the split: everything inlo..jis<=pivot and everything inj+1..hiis>=pivot. Both pointers stop on elements equal to the pivot, so a run of equal values is split in the middle rather than piled on one side.
Here the walk of the two indices on a fixed pivot, with no randomness, on [4, 7, 1, 4, 9, 2] (pivot 4). i and j start one step outside the range (lo - 1 and hi + 1) so that the first thing each loop iteration does is step inward by one: that way the very first element examined is the first one inside the range, and the loop shape "step, then keep stepping while the value is on the correct side" needs no special first case.
def hoare_trace(a):
"""Hoare partition with the pivot already at a[0]; prints where i and j stop."""
lo, hi = 0, len(a) - 1
pivot = a[lo]
i, j = lo - 1, hi + 1
print(f"pivot {pivot}, list {a}, i starts at {i} and j at {j} (both outside the range)")
while True:
i += 1 # step once, then keep going while the value is smaller than the pivot
while a[i] < pivot:
i += 1
j -= 1 # step once, then keep going while the value is larger than the pivot
while a[j] > pivot:
j -= 1
print(f" i stops at {i} (value {a[i]}), j stops at {j} (value {a[j]})", end="")
if i >= j:
print(f" -> crossed, split after index {j}: left {a[:j + 1]}, right {a[j + 1:]}")
return j
a[i], a[j] = a[j], a[i]
print(f" -> swap -> {a}")
hoare_trace([4, 7, 1, 4, 9, 2])
Output (python:3.12):
pivot 4, list [4, 7, 1, 4, 9, 2], i starts at -1 and j at 6 (both outside the range)
i stops at 0 (value 4), j stops at 5 (value 2) -> swap -> [2, 7, 1, 4, 9, 4]
i stops at 1 (value 7), j stops at 3 (value 4) -> swap -> [2, 4, 1, 7, 9, 4]
i stops at 3 (value 7), j stops at 2 (value 1) -> crossed, split after index 2: left [2, 4, 1], right [7, 9, 4]
Both indices stop on values equal to the pivot (i at index 0, j at index 3), which is why equal values get swapped to opposite sides instead of piling up on one side. The third line shows the crossing: i is at 3 and j at 2, so the split is after index 2. A Lomuto partition (one scan index, pivot parked at the end, < test) puts all equal elements on one side, and the first-element Lomuto function in the code does exactly that on the all-equal input.
- Recursion: compute
j, callsorton the shorter oflo..jandj+1..hi, then setloorhito shrink the longer one and go round thewhileloop again. - Tiny ranges: below a small
cutoffthe code hands the range to insertion sort (shift each element left past larger ones), which has little overhead on a handful of elements.
import random
stats = {"comparisons": 0, "max_depth": 0}
def partition(a, lo, hi, rng):
"""Hoare partition around a random pivot value. Returns j with
a[lo..j] <= pivot <= a[j+1..hi], and lo <= j < hi."""
k = rng.randint(lo, hi)
a[lo], a[k] = a[k], a[lo] # move the random pivot to the front
pivot = a[lo]
i, j = lo - 1, hi + 1
while True:
i += 1
stats["comparisons"] += 1
while a[i] < pivot:
i += 1
stats["comparisons"] += 1
j -= 1
stats["comparisons"] += 1
while a[j] > pivot:
j -= 1
stats["comparisons"] += 1
if i >= j:
return j
a[i], a[j] = a[j], a[i]
def insertion_sort(a, lo, hi):
for i in range(lo + 1, hi + 1):
item, j = a[i], i - 1
while j >= lo:
stats["comparisons"] += 1
if a[j] > item:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = item
def quicksort(a, rng, trace=False, cutoff=0):
"""In-place quicksort. Recurse into the smaller side, loop on the larger,
so the call stack never holds more than about log2(n) frames."""
def sort(lo, hi, depth):
stats["max_depth"] = max(stats["max_depth"], depth)
while lo < hi:
if hi - lo + 1 <= cutoff: # tiny range: insertion sort finishes it
insertion_sort(a, lo, hi)
return
j = partition(a, lo, hi, rng)
if trace:
print(f" partition [{lo}..{hi}] -> split after index {j}: {a}")
if j - lo < hi - j: # left side is smaller
sort(lo, j, depth + 1)
lo = j + 1 # keep looping on the right side
else:
sort(j + 1, hi, depth + 1)
hi = j # keep looping on the left side
sort(0, len(a) - 1, 1)
def naive_first_pivot(a, lo=0, hi=None):
"""Lomuto partition, first element as pivot, recurses on both sides."""
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
pivot, i = a[lo], lo
for j in range(lo + 1, hi + 1):
if a[j] < pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[lo], a[i] = a[i], a[lo]
naive_first_pivot(a, lo, i - 1)
naive_first_pivot(a, i + 1, hi)
def run(a, seed=1, cutoff=0):
stats["comparisons"] = 0
stats["max_depth"] = 0
b = list(a)
quicksort(b, random.Random(seed), cutoff=cutoff)
assert b == sorted(a)
return stats["comparisons"], stats["max_depth"]
if __name__ == "__main__":
data = [5, 2, 9, 2, 7, 1, 8, 3]
print("start:", data)
quicksort(data, random.Random(4), trace=True)
print("sorted:", data)
print("\nn, input -> comparisons, comparisons / (n*log2 n), max stack depth")
import math
for n in (1000, 4000, 16000, 64000):
rnd = random.Random(7)
inputs = {
"random": [rnd.randint(0, 10**9) for _ in range(n)],
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"all equal": [42] * n,
}
for name, arr in inputs.items():
c, d = run(arr)
print(f"{n:6d} {name:9s} -> {c:8d} {c / (n * math.log2(n)):.2f} depth {d}")
rnd = random.Random(7)
sample = [rnd.randint(0, 10**9) for _ in range(16000)]
for cutoff in (0, 16):
print(f"cutoff {cutoff:2d} on 16000 random values: comparisons {run(sample, cutoff=cutoff)[0]}")
# Edge cases and a randomized self-check against sorted().
rnd = random.Random(3)
for arr in ([], [1], [2, 1], [3, 3, 3]):
b = list(arr)
quicksort(b, random.Random(0))
assert b == sorted(arr)
for _ in range(500):
arr = [rnd.randint(0, 6) for _ in range(rnd.randint(0, 30))]
b = list(arr)
quicksort(b, random.Random(rnd.random()), cutoff=rnd.choice((0, 4)))
assert b == sorted(arr)
print("\nedge cases and 500 random arrays with many duplicates: ok")
# The contrast: first-element pivot, recursing on both sides.
for name, arr in (("sorted", list(range(5000))), ("all equal", [42] * 5000)):
try:
naive_first_pivot(arr)
print(f"first-element pivot, {name} input: finished")
except RecursionError:
print(f"first-element pivot, {name} input (n=5000): RecursionError")
Run in a python:3.12 container (Python 3.12), it prints:
start: [5, 2, 9, 2, 7, 1, 8, 3]
partition [0..7] -> split after index 1: [1, 2, 9, 5, 7, 2, 8, 3]
partition [0..1] -> split after index 0: [1, 2, 9, 5, 7, 2, 8, 3]
partition [2..7] -> split after index 6: [1, 2, 3, 5, 7, 2, 8, 9]
partition [2..6] -> split after index 2: [1, 2, 2, 5, 7, 3, 8, 9]
partition [3..6] -> split after index 5: [1, 2, 2, 5, 7, 3, 8, 9]
partition [3..5] -> split after index 3: [1, 2, 2, 3, 7, 5, 8, 9]
partition [4..5] -> split after index 4: [1, 2, 2, 3, 5, 7, 8, 9]
sorted: [1, 2, 2, 3, 5, 7, 8, 9]
n, input -> comparisons, comparisons / (n*log2 n), max stack depth
1000 random -> 15304 1.54 depth 8
1000 sorted -> 14594 1.46 depth 8
1000 reversed -> 14955 1.50 depth 7
1000 all equal -> 11862 1.19 depth 10
4000 random -> 73531 1.54 depth 9
4000 sorted -> 69376 1.45 depth 9
4000 reversed -> 74708 1.56 depth 9
4000 all equal -> 55454 1.16 depth 12
16000 random -> 318773 1.43 depth 11
16000 sorted -> 324427 1.45 depth 10
16000 reversed -> 328504 1.47 depth 11
16000 all equal -> 253822 1.14 depth 14
64000 random -> 1458081 1.43 depth 12
64000 sorted -> 1484606 1.45 depth 12
64000 reversed -> 1547808 1.51 depth 11
64000 all equal -> 1143294 1.12 depth 16
cutoff 0 on 16000 random values: comparisons 318773
cutoff 16 on 16000 random values: comparisons 278838
edge cases and 500 random arrays with many duplicates: ok
first-element pivot, sorted input (n=5000): RecursionError
first-element pivot, all equal input (n=5000): RecursionError
Reading the trace
Each partition line shows the list right after one partition step, with the range just partitioned and the split index.
partition [0..7] -> split after index 1: the left part is[1, 2], the right part is[9, 5, 7, 2, 8, 3]. The biggest element on the left (2) is not larger than the smallest on the right (2), which is exactly what a valid split needs. Equal values may land on either side.partition [2..7] -> split after index 6: the right part is just index 7 (value 9). That side is the smaller one, so the code recurses on it (it returns at once and prints nothing) and loops on[2..6], which is the next line.partition [3..6]and[3..5]keep carving off the larger remainder in the same way, until[4..5]leaves the list fully sorted:[1, 2, 2, 3, 5, 7, 8, 9].
Complexity, with the reasons
| Quantity | Value for the shipped code | Reason |
|---|---|---|
| Expected time | O(n log n) | A random pivot lands in the middle half of the sorted order half of the time, and then both sides hold at most three quarters of the range, so the sizes shrink geometrically on average and the depth of the splitting is O(log n), while each level touches n elements. Big-O notation here means growth with n: O(n log n) is slightly more than proportional to n. The textbook count for a random pivot is about 2 n ln n comparisons (ln is the natural logarithm, base e), which is about 1.39 n log2 n. |
| Measured growth | comparisons / (n log2 n) stays between 1.12 and 1.56 for n from 1000 to 64000 | The table counts comparisons, not seconds. A ratio that stays flat while n grows 64 times is n log n growth. |
| Worst-case time | O(n^2) | Happens only if the random draws keep landing on the smallest or largest element of the range. Which input you feed in does not change the growth: in the table sorted and reversed inputs stay within about 6 percent of the random count, and all-equal input costs 20 to 25 percent fewer comparisons because Hoare partition splits a run of equal values in the middle. |
| Extra space | O(log n) | No auxiliary arrays. The stack depth is at most floor(log2 n) + 1; the table shows depth 16 for n = 64000 (floor(log2 64000) is 15). |
| Stable? | No | Swaps across long distances reorder equal keys. |
If the interviewer wants a guaranteed O(n log n) worst case, say so: switch to heapsort when the depth passes about 2 log2 n (this hybrid is called introsort), or pick the pivot with median-of-medians (a selection method that guarantees a pivot not too close to either end, at a higher constant cost; heapsort is an O(n log n) sort built on a binary heap that never degrades). Randomization gives expected, not guaranteed, O(n log n).
The cutoff line in the output shows the insertion-sort option on the same 16000 random values: 318773 comparisons with no cutoff and 278838 with a cutoff of 16. That is one input size and one seed, so read it as "worth trying and measuring", not as a rule.
Edge cases and common mistakes
- Empty list, one element, two elements and all-equal values are all asserted in the driver, together with 500 random arrays full of duplicates.
- Recursing on both sides "because the code is shorter" gives O(n) stack in the unlucky case and a
RecursionErrorin Python. - With Hoare partition the pivot must be read from the position the loop starts at (
lohere). Usinga[hi]as the pivot with this loop shape can return a split that never shrinks the range, so the outerwhileloop never ends ([1, 2]loops forever). - Using
<=and>=in the innerwhileloops makes the pointers run past equal elements and off the end of the range: with this loop shape even[1, 2]raisesIndexError. - Calling
random.choice(a)returns a value, not an index; the swap needs the index. - Calling it stable. It is not; sort tagged records with
sortedor merge sort when ties must keep their order.
Running the code
Save the program as quicksort_demo.py and run:
python quicksort_demo.py
Standard library only (random, math); no install or config needed.
How deep can the call stack get in a recursive quicksort and in a recursive merge sort, including on already-sorted or reverse-sorted input? What would you change to keep stack usage bounded in production?
Sample Answer
The short answer
The call stack is the region of memory that holds one frame (a block with the arguments, local variables and return address) for every function call that has started but not yet returned. The depth of a recursive sort is how many of its calls are active at once.
- Merge sort splits the range by position (the middle index), never by value, so its depth is
ceil(log2 n)for every input order: sorted, reverse-sorted, all equal and random all give the same number. - Quicksort splits by value around a pivot (the reference key), so its depth depends on the pivot rule. With the last element as pivot, a sorted, reverse-sorted or all-equal input peels off one element per call, so the depth is n - 1. A random input gives a depth of roughly twice log2 n at the sizes measured below.
- To bound the stack in production: recurse only on the smaller side of the partition and loop on the larger side (depth at most
floor(log2 n)for any input and any pivot rule), or keep the pending ranges in an explicit stack with the same rule. A better pivot (random, median of three) protects the running time, but only the smaller-side rule guarantees the stack.
Measuring it
The program counts active partitioning (or splitting) calls for four input shapes. "Recurse both" is the textbook version (pivot = last element, Lomuto partition as described below, recursion on both sides). "Smaller first" recurses on the smaller side and loops on the larger. "Explicit stack" has no recursion: it pushes the larger side as a pending range and keeps working on the smaller side, and the table reports the largest number of pending ranges. The merge sort section checks the depth formula for n = 0, 1, 2, 3, 4, 5, 64, 100 and 1000. In the tables, bound is floor(log2 n), the limit the smaller-side rule guarantees it will not exceed (it is an upper limit, not always reached: no input of 4 keys gets deeper than 1); a measured value at or below it is the guarantee holding.
import random
import resource
import sys
def partition_last(a, lo, hi):
"""Lomuto partition with the LAST element as pivot."""
pivot, store = a[hi], lo
for i in range(lo, hi):
if a[i] < pivot:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi] = a[hi], a[store]
return store
def quick_plain(a, lo, hi, depth, stats):
"""Recurses on both sides. depth counts active partitioning calls."""
if lo >= hi:
return
stats[0] = max(stats[0], depth)
p = partition_last(a, lo, hi)
quick_plain(a, lo, p - 1, depth + 1, stats)
quick_plain(a, p + 1, hi, depth + 1, stats)
def quick_smaller_first(a, lo, hi, depth, stats):
"""Recurses on the smaller side, loops on the larger."""
while lo < hi:
stats[0] = max(stats[0], depth)
p = partition_last(a, lo, hi)
if p - lo < hi - p:
quick_smaller_first(a, lo, p - 1, depth + 1, stats)
lo = p + 1
else:
quick_smaller_first(a, p + 1, hi, depth + 1, stats)
hi = p - 1
def quick_explicit_stack(a):
"""No recursion: a stack of pending ranges, larger side pushed, smaller side processed first."""
pending = [(0, len(a) - 1)]
biggest = 0
while pending:
lo, hi = pending.pop()
while lo < hi:
p = partition_last(a, lo, hi)
if p - lo < hi - p:
pending.append((p + 1, hi))
hi = p - 1
else:
pending.append((lo, p - 1))
lo = p + 1
biggest = max(biggest, len(pending))
return biggest
def merge_top_down(a, lo, hi, depth, stats):
"""hi is exclusive. depth counts active calls on ranges of 2+ elements."""
if hi - lo < 2:
return
stats[0] = max(stats[0], depth)
mid = (lo + hi) // 2
merge_top_down(a, lo, mid, depth + 1, stats)
merge_top_down(a, mid, hi, depth + 1, stats)
a[lo:hi] = merge(a[lo:mid], a[mid:hi])
def merge(left, right):
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if right[j] < left[i]:
out.append(right[j]); j += 1
else:
out.append(left[i]); i += 1
return out + left[i:] + right[j:]
def merge_bottom_up(a):
"""No recursion at all: merge runs of width 1, 2, 4, ..."""
width = 1
while width < len(a):
for lo in range(0, len(a), 2 * width):
a[lo:lo + 2 * width] = merge(a[lo:lo + width], a[lo + width:lo + 2 * width])
width *= 2
def measure(fn, data):
stats = [0]
a = list(data)
fn(a, 0, len(a) - 1 if fn is not merge_top_down else len(a), 1, stats)
assert a == sorted(data)
return stats[0]
def shapes(n):
return {
"sorted": list(range(n)),
"reverse": list(range(n, 0, -1)),
"all equal": [3] * n,
"random": random.Random(n).sample(range(n), n),
}
print("Quicksort, pivot = last element (depth = active partitioning calls)")
print(f"{'input':<11}{'n':>5}{'recurse both':>14}{'smaller first':>15}{'explicit stack':>16}{'bound':>7}")
for n in (100, 200, 400):
for name, data in shapes(n).items():
both = measure(quick_plain, data)
small = measure(quick_smaller_first, data)
a = list(data)
stack = quick_explicit_stack(a)
assert a == sorted(data)
bound = n.bit_length() - 1 # floor(log2 n) for n >= 2
assert small <= bound and stack <= bound
print(f"{name:<11}{n:>5}{both:>14}{small:>15}{stack:>16}{bound:>7}")
print("\nsmaller-first / explicit stack at tiny sizes (bound is 0 for n < 2, floor(log2 n) otherwise)")
for n in range(0, 6):
data = list(range(n))
stats = [0]
quick_smaller_first(list(data), 0, n - 1, 1, stats)
a = list(data)
stack = quick_explicit_stack(a)
bound = 0 if n < 2 else n.bit_length() - 1
assert stats[0] <= bound and stack <= bound
print(f"n={n} smaller-first depth={stats[0]} stack entries={stack} bound={bound}")
print("\nMerge sort, top down (depth = active calls on 2+ elements)")
print(f"{'n':>5}{'sorted':>8}{'reverse':>9}{'all equal':>11}{'random':>8}{'ceil(log2 n)':>14}")
for n in (0, 1, 2, 3, 4, 5, 64, 100, 1000):
row = [measure(merge_top_down, d) for d in shapes(n).values()]
bound = (n - 1).bit_length() if n >= 2 else 0
assert all(r == bound for r in row)
print(f"{n:>5}{row[0]:>8}{row[1]:>9}{row[2]:>11}{row[3]:>8}{bound:>14}")
data = random.Random(5).sample(range(1000), 1000)
a = list(data)
merge_bottom_up(a)
assert a == sorted(data)
print("\nbottom-up merge sort: sorted 1000 shuffled keys with no recursive calls")
print("\nStack bytes = depth x frame size. Frame size F depends on language and compiler;")
print("F = 64 bytes below is an assumed illustration, not a measurement.")
soft = resource.getrlimit(resource.RLIMIT_STACK)[0]
print(f"main-thread stack limit in this container: {soft} bytes; CPython recursion limit: {sys.getrecursionlimit()} calls")
n, F = 10**6, 64
plain_depth = n - 1 # one active call per key except the last, as in the tables above
print(f"n={n}: last-pivot quicksort on sorted input: depth {plain_depth} x {F} = {plain_depth * F} bytes ({plain_depth * F / 2**20:.1f} MiB)")
d = n.bit_length() - 1
print(f"n={n}: smaller-side-first: depth <= {d} x {F} = {d * F} bytes")
Complete output:
Quicksort, pivot = last element (depth = active partitioning calls)
input n recurse both smaller first explicit stack bound
sorted 100 99 1 1 6
reverse 100 99 1 1 6
all equal 100 99 1 1 6
random 100 11 4 4 6
sorted 200 199 1 1 7
reverse 200 199 1 1 7
all equal 200 199 1 1 7
random 200 15 4 4 7
sorted 400 399 1 1 8
reverse 400 399 1 1 8
all equal 400 399 1 1 8
random 400 18 6 6 8
smaller-first / explicit stack at tiny sizes (bound is 0 for n < 2, floor(log2 n) otherwise)
n=0 smaller-first depth=0 stack entries=0 bound=0
n=1 smaller-first depth=0 stack entries=0 bound=0
n=2 smaller-first depth=1 stack entries=1 bound=1
n=3 smaller-first depth=1 stack entries=1 bound=1
n=4 smaller-first depth=1 stack entries=1 bound=2
n=5 smaller-first depth=1 stack entries=1 bound=2
Merge sort, top down (depth = active calls on 2+ elements)
n sorted reverse all equal random ceil(log2 n)
0 0 0 0 0 0
1 0 0 0 0 0
2 1 1 1 1 1
3 2 2 2 2 2
4 2 2 2 2 2
5 3 3 3 3 3
64 6 6 6 6 6
100 7 7 7 7 7
1000 10 10 10 10 10
bottom-up merge sort: sorted 1000 shuffled keys with no recursive calls
Stack bytes = depth x frame size. Frame size F depends on language and compiler;
F = 64 bytes below is an assumed illustration, not a measurement.
main-thread stack limit in this container: 8388608 bytes; CPython recursion limit: 1000 calls
n=1000000: last-pivot quicksort on sorted input: depth 999999 x 64 = 63999936 bytes (61.0 MiB)
n=1000000: smaller-side-first: depth <= 19 x 64 = 1216 bytes
Small pictures: why sorted input is deep, why merge sort is shallow, what the stack holds
Three tiny runs before the big table. The Lomuto partition scans left to right and keeps a boundary store: each key smaller than the pivot is swapped to the front of the boundary, and at the end the pivot is swapped into the boundary slot, where it stays. The first run applies it to sorted [1, 2, 3, 4] with the last element as pivot. The second prints the ranges merge sort visits for 8 keys. The third prints the pending-range stack of the explicit-stack quicksort on 8 keys.
def partition_last(a, lo, hi):
"""Lomuto partition with the LAST element as pivot."""
pivot, store = a[hi], lo
for i in range(lo, hi):
if a[i] < pivot:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi] = a[hi], a[store]
return store
print("1. Lomuto partition with the last element as pivot on sorted [1, 2, 3, 4]")
a = [1, 2, 3, 4]
p = partition_last(a, 0, 3)
print(f" pivot 4 ends at index {p}: left side has {p} keys, right side has {3 - p} keys, array {a}")
print("\n2. Merge sort splits by position: ranges for 8 keys (half-open lo..hi)")
def halving(lo, hi, depth):
if hi - lo < 2:
return depth - 1
print(f" {' ' * (depth - 1)}depth {depth}: range {lo}..{hi} ({hi - lo} keys)")
mid = (lo + hi) // 2
return max(halving(lo, mid, depth + 1), halving(mid, hi, depth + 1), depth)
print(" deepest call that has 2 or more keys: depth", halving(0, 8, 1))
print("\n3. Explicit stack of pending ranges, last-element pivot, on [5, 2, 8, 1, 9, 3, 7, 4]")
a = [5, 2, 8, 1, 9, 3, 7, 4]
pending = [(0, len(a) - 1)]
biggest = 0
while pending:
lo, hi = pending.pop()
print(f" take range {lo}..{hi}")
while lo < hi:
p = partition_last(a, lo, hi)
if p - lo < hi - p:
pending.append((p + 1, hi))
hi = p - 1
kept = "left (smaller) side kept, right side pushed"
else:
pending.append((lo, p - 1))
lo = p + 1
kept = "right (smaller or equal) side kept, left side pushed"
biggest = max(biggest, len(pending))
print(f" partition at {p}: {kept}; pending now {pending}; array {a}")
print(" sorted:", a, "| most pending ranges at once:", biggest)
Run in a python:3.12 container, it prints:
1. Lomuto partition with the last element as pivot on sorted [1, 2, 3, 4]
pivot 4 ends at index 3: left side has 3 keys, right side has 0 keys, array [1, 2, 3, 4]
2. Merge sort splits by position: ranges for 8 keys (half-open lo..hi)
depth 1: range 0..8 (8 keys)
depth 2: range 0..4 (4 keys)
depth 3: range 0..2 (2 keys)
depth 3: range 2..4 (2 keys)
depth 2: range 4..8 (4 keys)
depth 3: range 4..6 (2 keys)
depth 3: range 6..8 (2 keys)
deepest call that has 2 or more keys: depth 3
3. Explicit stack of pending ranges, last-element pivot, on [5, 2, 8, 1, 9, 3, 7, 4]
take range 0..7
partition at 3: left (smaller) side kept, right side pushed; pending now [(4, 7)]; array [2, 1, 3, 4, 9, 8, 7, 5]
partition at 2: right (smaller or equal) side kept, left side pushed; pending now [(4, 7), (0, 1)]; array [2, 1, 3, 4, 9, 8, 7, 5]
take range 0..1
partition at 0: left (smaller) side kept, right side pushed; pending now [(4, 7), (1, 1)]; array [1, 2, 3, 4, 9, 8, 7, 5]
take range 1..1
take range 4..7
partition at 4: left (smaller) side kept, right side pushed; pending now [(5, 7)]; array [1, 2, 3, 4, 5, 8, 7, 9]
take range 5..7
partition at 7: right (smaller or equal) side kept, left side pushed; pending now [(5, 6)]; array [1, 2, 3, 4, 5, 8, 7, 9]
take range 5..6
partition at 5: left (smaller) side kept, right side pushed; pending now [(6, 6)]; array [1, 2, 3, 4, 5, 7, 8, 9]
take range 6..6
sorted: [1, 2, 3, 4, 5, 7, 8, 9] | most pending ranges at once: 2
Reading it. In run 1 the pivot 4 is bigger than every other key, so the split is 3 keys against 0: one call per key, which is where depth n - 1 comes from. In run 2 each range is cut at its middle index whatever the values are, so 8 keys halve to 4, 2 and then single keys: 3 levels, which is log2 8. In run 3 only ranges still waiting to be sorted are on the stack, and the smaller side is always handled first, so the stack never held more than 2 ranges for 8 keys.
Reading the output
- Quicksort, worst case. For sorted, reverse-sorted and all-equal inputs the plain version's depth is 99, 199 and 399 for n = 100, 200, 400: exactly n - 1. On random input it is 11, 15 and 18 for the same n.
- Smaller side first. The depth is 1 for the three degenerate shapes (the smaller side is empty, so the work is a loop) and 4, 4, 6 on random input. The bound
floor(log2 n)(6, 7, 8) holds in every row, and in the tiny-size table it holds at n = 0, 1 and 2 (depth 0, 0, 1). Why: the side that is recursed on has at most half the elements, so each active call has at most half as many as its parent. - Explicit stack. The largest number of pending ranges equals the smaller-first depth in every row, for the same reason.
- Merge sort. The depth equals
ceil(log2 n)in every cell: 0 for n = 0 and 1, 1 for n = 2, 7 for n = 100, 10 for n = 1000, whatever the input order. - Iterative merge sort. The bottom-up version merges runs of width 1, 2, 4, ... with a loop and no recursion at all. It sorted 1000 shuffled keys correctly.
Stack bytes
The tables above are measurements of depth; the byte figures here are a back-of-envelope scaling of those depths. The stack space used is the depth multiplied by the frame size F: bytes = depth x F. F depends on the language, compiler and optimization level, so the program uses F = 64 bytes as an assumed illustration, not a measurement. For n = 1,000,000: the last-pivot quicksort on sorted input needs depth 999,999, which is 63,999,936 bytes (61.0 MiB), far above the 8,388,608-byte (8 MiB) main-thread stack limit that this Linux container reported (the operating system's cap on how large the main thread's stack may grow, read by the program through RLIMIT_STACK), so the process would crash. The smaller-side rule needs at most 19 frames, which is 1,216 bytes. (CPython enforces its own limit of 1000 nested calls, printed above, so a Python run of the plain version fails on large sorted input long before an 8 MiB stack matters.)
Merge sort's real memory cost is not the stack but its auxiliary buffer for merging, O(n) in the usual implementations, which lives on the heap.
Languages without tail-call optimization
The second recursive call of the plain quicksort is a tail call: a call that is the very last thing the function does, so nothing is left to do in the caller afterwards (as in return countdown(n - 1)). The caller's frame is then no longer needed, so a compiler is allowed to reuse it: that is tail-call optimization. Some compilers turn it into a jump, but neither Python nor the C and C++ standards require that, so correct code cannot rely on it. The loop on the larger side in "smaller first" is the same transformation done by hand, and it guarantees the bound in every language.
Common mistakes
- Recursing on the larger side first, or on both sides without a rule, and assuming "average depth is log n" is a guarantee.
- Fixing the pivot rule only: median of three makes the sorted case fine, yet adversarial inputs for any fixed rule remain.
- Believing merge sort's recursion is shallow because it is "balanced": true, but its extra memory is O(n).
Running the code
python3 sort_stack_depth.py # Python 3.12, standard library only
python3 stack_pictures.py # the small pictures listing
List common off-by-one mistakes and mid-calculation errors that cause binary search implementations to loop infinitely or return incorrect indices. For each mistake give a short example input that breaks the incorrect implementation and explain the root cause.
Sample Answer
The idea in plain words
A binary search is a loop that keeps a window [lo, hi] of positions where the target could still be, and shrinks it using the middle element. Almost every bug is a mismatch between three choices that must agree: what the window means (does hi point at a real candidate, or one past the end?), when the loop stops (lo <= hi or lo < hi), and how the window shrinks (mid + 1, mid - 1, or mid). A mismatch skips a candidate, or leaves the window the same size so the loop never ends.
The correct closed-window version has this invariant, in words: if the target is in the list, it is somewhere in a[lo..hi], both ends included. The loop runs while the window is non-empty (lo <= hi), and each step removes mid from the window, so it must shrink.
The programs
Buggy functions 1 to 5 below each change one thing from correct; 6 and 7 are first-occurrence and last-occurrence searches with one thing wrong. To make an endless loop visible instead of hanging the program, the runner passes a list subclass that raises an error after 100 reads (Looping); a correct search on these tiny lists never gets near that. In Guarded, the method __getitem__ is what Python calls for every a[i], so each read adds one to reads, and super().__getitem__(i) then does the ordinary list read. The block that prints the int32 line runs the midpoint formula over a virtual sorted array of two billion items (nothing is stored: the value at index i is just i), with a function that wraps the sum the way a signed 32-bit integer does.
import itertools
class Looping(Exception):
pass
class Guarded(list):
"""A list that raises Looping after too many reads, so an infinite loop shows up as an error."""
reads = 0
def __getitem__(self, i):
self.reads += 1
if self.reads > 100:
raise Looping("more than 100 reads")
return super().__getitem__(i)
def correct(a, t): # closed window [lo, hi]; invariant: t, if present, is in a[lo..hi]
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_strict_loop(a, t): # 1. 'lo < hi' with a closed window
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_lo_equals_mid(a, t): # 2. 'lo = mid' never shrinks the window
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid
else:
hi = mid - 1
return -1
def bug_hi_equals_mid(a, t): # 3. 'hi = mid' with a closed window
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid
return -1
def bug_hi_is_len(a, t): # 4. hi = len(a) but the loop treats hi as inclusive
lo, hi = 0, len(a)
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_float_mid(a, t): # 5. '/' instead of '//' in Python 3
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) / 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def first_ge(a, t): # reference: first index with a[i] >= t
return next((i for i, x in enumerate(a) if x >= t), len(a))
def bug_first_occurrence(a, t): # 6. half-open window but 'hi = mid - 1'
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] >= t:
hi = mid - 1
else:
lo = mid + 1
return lo
def last_le(a, t): # reference: last index with a[i] <= t, or -1
return max((i for i, x in enumerate(a) if x <= t), default=-1)
def bug_last_occurrence(a, t): # 7. 'lo = mid' needs the upper middle, but mid rounds down
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] <= t:
lo = mid
else:
hi = mid - 1
return lo if a and a[lo] <= t else -1
def first_ge_fixed(a, t): # half-open window: hi = mid keeps a possible answer
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] >= t:
hi = mid
else:
lo = mid + 1
return lo
def last_le_fixed(a, t): # closed window, 'lo = mid' paired with the upper middle
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if a[mid] <= t:
lo = mid
else:
hi = mid - 1
return lo if a and a[lo] <= t else -1
def run(fn, a, t):
try:
return fn(Guarded(a), t)
except Looping:
return "infinite loop"
except Exception as e:
return type(e).__name__
def to_int32(x):
x &= 0xFFFFFFFF
return x - (1 << 32) if x >= (1 << 31) else x
def search_virtual(n, target, midpoint):
"""Binary search over the virtual sorted array [0, 1, ..., n-1]."""
lo, hi = 0, n - 1
steps = []
while lo <= hi:
mid = midpoint(lo, hi)
steps.append((lo, hi, mid))
if mid < 0:
return "negative index " + str(mid), steps
if mid == target:
return mid, steps
if mid < target:
lo = mid + 1
else:
hi = mid - 1
return -1, steps
cases = [
("1 strict loop ", bug_strict_loop, [1, 3, 5], 5),
("1 strict loop ", bug_strict_loop, [4], 4),
("2 lo = mid ", bug_lo_equals_mid, [1, 3], 3),
("3 hi = mid ", bug_hi_equals_mid, [1, 3], 0),
("4 hi = len(a) ", bug_hi_is_len, [1, 3, 5], 9),
("5 mid = (lo+hi)/2 ", bug_float_mid, [1, 3, 5], 3),
]
for name, fn, a, t in cases:
print(f"{name} a={a} target={t}: buggy={run(fn, a, t)} correct={correct(a, t)}")
for name, fn, ref, a, t in [
("6 first, hi=mid-1 ", bug_first_occurrence, first_ge, [1, 2, 3, 3], 3),
("7 last, lo=mid ", bug_last_occurrence, last_le, [1, 2], 2),
]:
print(f"{name} a={a} target={t}: buggy={run(fn, a, t)} correct={ref(a, t)}")
# Every non-decreasing list of length 0..5 over the values 0..3, with targets -1..4.
inputs = [(list(c), t) for n in range(6)
for c in itertools.combinations_with_replacement(range(4), n) for t in range(-1, 5)]
print("\ninputs per check:", len(inputs))
def fails(fn, expect):
bad = 0
for a, t in inputs:
got = run(fn, a, t)
bad += got != expect(a, t)
return bad
for name, fn in [("correct", correct), ("bug 1", bug_strict_loop), ("bug 2", bug_lo_equals_mid),
("bug 3", bug_hi_equals_mid), ("bug 4", bug_hi_is_len), ("bug 5", bug_float_mid)]:
bad = 0
for a, t in inputs:
got = run(fn, a, t)
ok = isinstance(got, int) and ((got == -1 and t not in a) or (got != -1 and a[got] == t))
bad += not ok
print(f"{name:8} wrong or crashing on {bad} inputs")
print("bug 6 wrong on", fails(bug_first_occurrence, first_ge), "inputs")
print("bug 7 wrong on", fails(bug_last_occurrence, last_le), "inputs")
print("fixed 6 wrong on", fails(first_ge_fixed, first_ge), "inputs")
print("fixed 7 wrong on", fails(last_le_fixed, last_le), "inputs")
print()
n = 2_000_000_000
total = 1_000_000_000 + 1_999_999_999
print(f"int32 maximum 2,147,483,647; sum {total:,} wraps to {to_int32(total):,} "
f"(= {total:,} - 2**32), halved with // gives {to_int32(total) // 2:,}")
for label, mid in [("(lo+hi)//2 in int32", lambda lo, hi: to_int32(lo + hi) // 2),
("lo+(hi-lo)//2 ", lambda lo, hi: lo + (hi - lo) // 2)]:
result, steps = search_virtual(n, n - 1, mid)
print(f"{label}: result={result} after {len(steps)} steps; last (lo, hi, mid) = {steps[-1]}")
print()
a, t = [1, 3, 5, 7], 4
lo, hi = 0, len(a) - 1
print(f"correct search for {t} in {a}:")
while lo <= hi:
mid = lo + (hi - lo) // 2
print(f" lo={lo} hi={hi} mid={mid} a[mid]={a[mid]}")
if a[mid] == t:
break
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
print(f" ends with lo={lo} hi={hi}: empty window, return -1")
The output below is the complete output of that program.
1 strict loop a=[1, 3, 5] target=5: buggy=-1 correct=2
1 strict loop a=[4] target=4: buggy=-1 correct=0
2 lo = mid a=[1, 3] target=3: buggy=infinite loop correct=1
3 hi = mid a=[1, 3] target=0: buggy=infinite loop correct=-1
4 hi = len(a) a=[1, 3, 5] target=9: buggy=IndexError correct=-1
5 mid = (lo+hi)/2 a=[1, 3, 5] target=3: buggy=TypeError correct=1
6 first, hi=mid-1 a=[1, 2, 3, 3] target=3: buggy=1 correct=2
7 last, lo=mid a=[1, 2] target=2: buggy=infinite loop correct=1
inputs per check: 756
correct wrong or crashing on 0 inputs
bug 1 wrong or crashing on 87 inputs
bug 2 wrong or crashing on 323 inputs
bug 3 wrong or crashing on 265 inputs
bug 4 wrong or crashing on 211 inputs
bug 5 wrong or crashing on 750 inputs
bug 6 wrong on 102 inputs
bug 7 wrong on 446 inputs
fixed 6 wrong on 0 inputs
fixed 7 wrong on 0 inputs
int32 maximum 2,147,483,647; sum 2,999,999,999 wraps to -1,294,967,297 (= 2,999,999,999 - 2**32), halved with // gives -647,483,649
(lo+hi)//2 in int32: result=negative index -647483649 after 2 steps; last (lo, hi, mid) = (1000000000, 1999999999, -647483649)
lo+(hi-lo)//2 : result=1999999999 after 31 steps; last (lo, hi, mid) = (1999999999, 1999999999, 1999999999)
correct search for 4 in [1, 3, 5, 7]:
lo=0 hi=3 mid=1 a[mid]=3
lo=2 hi=3 mid=2 a[mid]=5
ends with lo=2 hi=1: empty window, return -1
The eight mistakes, each with its failing input and cause
- Loop condition
lo < hiwith a closed window. On[1, 3, 5], target 5, the window shrinks tolo=hi=2and the loop exits without ever looking at index 2, so the result is -1 instead of 2.[4]with target 4 fails the same way: the loop never starts. Root cause: withhia real candidate, a window of size one is still unsearched. Fix:lo <= hi. lo = midinstead ofmid + 1. On[1, 3], target 3:mid=0,a[0]=1 < 3, andlois set back to 0, so the window never changes. The guard reports an infinite loop. Root cause:midwas already inspected and rejected, so it must leave the window. Fix:lo = mid + 1.hi = midinstead ofmid - 1. On[1, 3], target 0:mid=0,a[0]=1 > 0,hi=0, and the next round repeats exactly. Same root cause as mistake 2, on the other side.hi = len(a)with an inclusive loop. On[1, 3, 5], target 9 the window reacheshi=3,mid=3, anda[3]raisesIndexError. Root cause: the code mixes the half-open convention (hiis one past the end) with the closed-window loop (lo <= hireadsa[hi]). Pick one convention and keep every line consistent with it./instead of//for the midpoint. In Python 3,(lo + hi) / 2is a float:a[1.0]raisesTypeErroron[1, 3, 5](every input with a non-empty list that reaches a probe, which is why 750 of 756 inputs fail). Habits from C and Java, where/on two integers gives an integer, cause this; use//.- First-occurrence search over a half-open window (
hi = len(a), looplo < hi) that setshi = mid - 1. On[1, 2, 3, 3], target 3 the buggy search returns 1, but the first index with a value >= 3 is 2. Root cause: for "first index that satisfies a condition",miditself may be the answer when the condition holds, so it must stay:hi = mid. Throwing it away silently skips the answer. The working form isfirst_ge_fixedin the listing:if a[mid] >= t: hi = mid, elselo = mid + 1, which fails on 0 of the 756 inputs. lo = midwhile searching for the last occurrence, withmidrounding down. On[1, 2], target 2:lo=0, hi=1, mid=0, the condition holds,lo = mid = 0again, and the window never shrinks. Root cause: when the update keepsmid(lo = mid), the midpoint must round up (the upper middle: for a window of two items, the right one) so it differs fromlo:mid = lo + (hi - lo + 1) // 2. The mirror rule: updates that keepmidon thehiside use the rounded-down midpoint. The working form islast_le_fixedin the listing, which also fails on 0 of the 756 inputs.- Midpoint overflow,
(lo + hi) // 2in a 32-bit signed integer. The last block searches the virtual array0..1,999,999,999for the value 1,999,999,999. A signed 32-bit integer holds values only up to 2,147,483,647. In Java a sum past that is defined to wrap around by 2^32 = 4,294,967,296 (in C and C++ signed overflow is itself undefined behaviour, and on common hardware it typically wraps the same way); the program emulates the wrapping. The first probe is safe (0 + 1,999,999,999 fits), and the search moves tolo=1,000,000,000andhi=1,999,999,999. Then the sum 2,999,999,999 is above the limit, so it wraps to 2,999,999,999 - 4,294,967,296 = -1,294,967,297, and the program's floor division gives -647,483,649 (both numbers are on the int32 line of the output, and the line after it prints the failing search): a negative index. Integer division in Java, C and C++ truncates toward zero instead of flooring, so(lo + hi) / 2there gives -647,483,648 for this sum (run in an eclipse-temurin:21-jdk container); either way the index is negative. In C and C++ an out-of-range read is undefined behaviour, meaning the language puts no requirement on what happens, so the program may crash or read garbage; other languages raise an exception or return the wrong element. Withlo + (hi - lo) // 2the same search ends at the right index after 31 steps. Python's integers never overflow, so this only appears in fixed-width languages or when you emulate them as above.
The counts after "inputs per check" come from running each version on all 756 non-decreasing lists of length 0 to 5 over the values 0 to 3, with every target from -1 to 4: the correct version fails on 0, and every buggy version fails on a different number of inputs. Mistake 6 and 7 are judged against a first-index-at-or-above and last-index-at-or-below reference, the others against "an index holding the target, or -1".
The correct version, step by step
The final block traces the correct search for the absent value 4 in [1, 3, 5, 7]: probe index 1 (value 3, too small) so lo=2; probe index 2 (value 5, too big) so hi=1. Now lo=2 > hi=1, the window is empty, and the function returns -1. The loop ends exactly when the window empties, which is why lo <= hi is the matching condition for a closed window.
A rule to keep
Choose a convention before writing any line, and check three things against it: the initial hi, the loop condition, and each update. Then run three inputs on a one-element list [4]: target 4 (a hit), target 0 (below everything) and target 9 (above everything). Those catch mistakes 1 to 4 immediately.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python binary_search_bugs.py
Save the program as binary_search_bugs.py. It uses only the standard library, and the output above is from Python 3.12.
Unlock Full Question Bank
Get access to all 7 Sorting and Searching Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.