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.
Given user records with name, age and signup timestamp, sort by age ascending and then by signup timestamp descending, keeping the sort stable. Show it with a comparator and with successive stable sorts, and say which you prefer.
Sample Answer
The idea in plain words
The order is two keys: age ascending, and among equal ages, signup timestamp descending (newest first). Three ways to get it with Python's sort, which is stable (equal elements keep their input order, so users who tie on both keys keep their original order):
- Comparator: one function that says which of two users goes first, wrapped with
functools.cmp_to_key. - Successive stable sorts: sort by the less important key first (signup descending), then by the more important key (age ascending). The second sort is stable, so within one age the signup order from the first sort survives.
- One key function returning a tuple:
(age, -signup). Tuples compare element by element, and negating a number flips its direction.
Which one to prefer
Prefer the single key function (option 3) when every descending key can be negated (numbers, timestamps). It is one pass, the key function runs once per record, and it is the shortest. Use successive stable sorts (option 2) when a descending key cannot be negated, for example a string sorted descending next to another ascending key; it also reads clearly as "sort by A, then by B" and works with reverse=True for each pass. Use a comparator (option 1) only when the ordering truly cannot be expressed as a key, because the comparator runs inside the sort on every comparison: for 50000 users it was called 714,542 times against 50,000 key calls.
Terms the code uses
- Key function: a function that takes one record and returns the value to sort by, for example
lambda u: u.age.sorted(users, key=...)calls it once per record and sorts by the returned values. lambda: a function written inline without a name;lambda u: u.ageis the same asdef f(u): return u.age.- Comparator: a function that takes two records and returns a negative number (first goes first), zero (tie) or a positive number (second goes first). Python's
sorteddoes not accept one directly. functools.cmp_to_key: an adapter that wraps a comparator so it can be passed askey=. Each record is wrapped in an object whose<calls the comparator.@dataclass(frozen=True): a short way to declare a record class with named fields;frozen=Trueforbids reassigning a field after creation.(a > b) - (a < b): comparisons giveTrueorFalse, which count as 1 and 0, so the difference is 1 when a is larger, 0 when equal and -1 when smaller.
The block below shows each of these in action, plus two comparator mistakes.
from dataclasses import FrozenInstanceError, dataclass
from functools import cmp_to_key
@dataclass(frozen=True) # a record class; frozen means fields cannot be reassigned
class Point:
x: int
y: int
def age_key(p): # a key function: one record in, one sortable value out
return p.x
same_key = lambda p: p.x # a lambda is the same function written inline, without a name
def old_style(a, b): # a comparator: two records in, a negative, zero or positive number out
return a.x - b.x
p, q = Point(2, 0), Point(1, 0)
try:
p.x = 5
except FrozenInstanceError:
print("frozen record cannot be changed")
print("key function and lambda agree:", age_key(p) == same_key(p))
wrapped_key = cmp_to_key(old_style) # cmp_to_key turns a comparator into a key function
print("cmp_to_key objects compare with <:", wrapped_key(p) < wrapped_key(q), wrapped_key(q) < wrapped_key(p))
print("sorted with comparator:", sorted([p, q], key=wrapped_key))
# (a > b) - (a < b): True counts as 1 and False as 0, so the result is -1, 0 or 1
print("three-way compare of (3,2), (2,2), (1,2):", [(a > b) - (a < b) for a, b in ((3, 2), (2, 2), (1, 2))])
# A comparator that returns a boolean never says "smaller", so the order is wrong
print("boolean comparator:", sorted([3, 1, 2], key=cmp_to_key(lambda a, b: a > b)))
print("correct comparator:", sorted([3, 1, 2], key=cmp_to_key(lambda a, b: (a > b) - (a < b))))
# a - b as a comparator is safe in Python, but a 32-bit int in C or Java wraps around
a, b = 2_000_000_000, -2_000_000_000
wrap32 = lambda v: (v + 2**31) % 2**32 - 2**31
print("a - b =", a - b, "| as a 32-bit signed int:", wrap32(a - b), "(sign flipped: a would sort before b)")
Run in a python:3.12 container (Python 3.12), it prints:
frozen record cannot be changed
key function and lambda agree: True
cmp_to_key objects compare with <: False True
sorted with comparator: [Point(x=1, y=0), Point(x=2, y=0)]
three-way compare of (3,2), (2,2), (1,2): [1, 0, -1]
boolean comparator: [3, 1, 2]
correct comparator: [1, 2, 3]
a - b = 4000000000 | as a 32-bit signed int: -294967296 (sign flipped: a would sort before b)
The code
sort_by_keys is a small helper for chaining: it takes (key function, descending) pairs, most important first, and applies one stable sort per pair starting from the last. The program also shows the wrong order of passes, checks every method and three named mistakes against a reference, a three-key ordering (score descending, latency ascending, id ascending) with a comparator and with a key function, and a descending string key.
import random
from dataclasses import dataclass
from functools import cmp_to_key
@dataclass(frozen=True)
class User:
name: str
age: int
signup: int # Unix timestamp in seconds
row: int # input position, only used to check that ties keep input order
def compare(x, y):
"""Age ascending, then signup descending. Returns <0, 0 or >0."""
if x.age != y.age:
return -1 if x.age < y.age else 1
if x.signup != y.signup:
return -1 if x.signup > y.signup else 1 # later signup sorts first
return 0
def sort_with_comparator(users):
calls = [0]
def counted(x, y):
calls[0] += 1
return compare(x, y)
return sorted(users, key=cmp_to_key(counted)), calls[0]
def sort_with_two_passes(users):
by_signup = sorted(users, key=lambda u: u.signup, reverse=True) # secondary key first
return sorted(by_signup, key=lambda u: u.age) # primary key last
def sort_with_tuple_key(users):
return sorted(users, key=lambda u: (u.age, -u.signup)) # negate the number to flip it
def sort_by_keys(items, *specs):
"""specs = (key_function, descending) pairs, most important first.
Applies one stable sort per spec, starting from the LAST (least important)."""
for key_fn, descending in reversed(specs):
items = sorted(items, key=key_fn, reverse=descending)
return items
if __name__ == "__main__":
users = [User("ann", 31, 500, 0), User("bo", 25, 900, 1), User("cy", 31, 700, 2),
User("di", 25, 900, 3), User("ed", 31, 500, 4), User("flo", 25, 100, 5)]
for label, result in (("comparator", sort_with_comparator(users)[0]),
("two passes", sort_with_two_passes(users)),
("tuple key", sort_with_tuple_key(users)),
("sort_by_keys", sort_by_keys(users, (lambda u: u.age, False),
(lambda u: u.signup, True)))):
print(f"{label:12s}", [(u.name, u.age, u.signup) for u in result])
wrong = sorted(sorted(users, key=lambda u: u.age), key=lambda u: u.signup, reverse=True)
print("wrong order ", [(u.name, u.age, u.signup) for u in wrong], "(primary key sorted first)")
# Ties: bo and di are identical on both keys, ann and ed too. Input order must survive.
result = sort_with_tuple_key(users)
print("ties keep input order:", [u.row for u in result if u.name in ("bo", "di")] == [1, 3]
and [u.row for u in result if u.name in ("ann", "ed")] == [0, 4])
# (score desc, latency asc, id asc): one comparator vs one key function.
rows = [("a7", 0.9, 120), ("b2", 0.9, 80), ("c1", 0.7, 80), ("d4", 0.9, 80)] # (id, score, latency)
def cmp_rows(x, y):
if x[1] != y[1]:
return -1 if x[1] > y[1] else 1
if x[2] != y[2]:
return -1 if x[2] < y[2] else 1
return (x[0] > y[0]) - (x[0] < y[0])
by_cmp = sorted(rows, key=cmp_to_key(cmp_rows))
by_key = sorted(rows, key=lambda r: (-r[1], r[2], r[0]))
print("score/latency/id:", [r[0] for r in by_cmp], by_cmp == by_key)
# Descending strings cannot be negated: successive stable passes handle them.
names = [("kim", 3), ("lee", 3), ("kay", 5)]
print("count asc, name desc:", sort_by_keys(names, (lambda r: r[1], False), (lambda r: r[0], True)))
# Cost: how many times does user code run for 50000 users?
rnd = random.Random(8)
many = [User(f"u{i}", rnd.randint(18, 70), rnd.randint(0, 10**6), i) for i in range(50_000)]
out_cmp, calls = sort_with_comparator(many)
out_key = sort_with_tuple_key(many)
assert out_cmp == out_key == sort_with_two_passes(many)
print(f"n=50000: comparator called {calls} times; key function called {len(many)} times")
# Self-check against a reference that spells the rule out (age, newest signup, input position).
# The four correct methods must match it on every input; the named mistakes must not.
def reference(us):
return sorted(us, key=lambda u: (u.age, -u.signup, u.row))
methods = {
"comparator": lambda us: sort_with_comparator(us)[0],
"two passes": sort_with_two_passes,
"tuple key": sort_with_tuple_key,
"sort_by_keys": lambda us: sort_by_keys(us, (lambda u: u.age, False), (lambda u: u.signup, True)),
"MISTAKE primary key first": lambda us: sorted(sorted(us, key=lambda u: u.age),
key=lambda u: u.signup, reverse=True),
"MISTAKE reverse=True on whole sort": lambda us: sorted(us, key=lambda u: (u.age, -u.signup), reverse=True),
"MISTAKE boolean comparator": lambda us: sorted(us, key=cmp_to_key(lambda x, y: x.age > y.age)),
}
differ = {name: 0 for name in methods}
for _ in range(300):
small = [User("x", rnd.randint(0, 2), rnd.randint(0, 2), i) for i in range(rnd.randint(0, 10))]
for name, fn in methods.items():
differ[name] += fn(small) != reference(small)
print("300 random tie-heavy inputs, how many differ from the reference:")
for name, count in differ.items():
print(f" {name:36s}{count}")
Run in a python:3.12 container (Python 3.12), it prints:
comparator [('bo', 25, 900), ('di', 25, 900), ('flo', 25, 100), ('cy', 31, 700), ('ann', 31, 500), ('ed', 31, 500)]
two passes [('bo', 25, 900), ('di', 25, 900), ('flo', 25, 100), ('cy', 31, 700), ('ann', 31, 500), ('ed', 31, 500)]
tuple key [('bo', 25, 900), ('di', 25, 900), ('flo', 25, 100), ('cy', 31, 700), ('ann', 31, 500), ('ed', 31, 500)]
sort_by_keys [('bo', 25, 900), ('di', 25, 900), ('flo', 25, 100), ('cy', 31, 700), ('ann', 31, 500), ('ed', 31, 500)]
wrong order [('bo', 25, 900), ('di', 25, 900), ('cy', 31, 700), ('ann', 31, 500), ('ed', 31, 500), ('flo', 25, 100)] (primary key sorted first)
ties keep input order: True
score/latency/id: ['b2', 'd4', 'a7', 'c1'] True
count asc, name desc: [('lee', 3), ('kim', 3), ('kay', 5)]
n=50000: comparator called 714542 times; key function called 50000 times
300 random tie-heavy inputs, how many differ from the reference:
comparator 0
two passes 0
tuple key 0
sort_by_keys 0
MISTAKE primary key first 185
MISTAKE reverse=True on whole sort 246
MISTAKE boolean comparator 221
Reading the output
- The four methods print the same order: age 25 first, newest signup first inside the age (
boanddiat 900, thenfloat 100), then age 31 (cyat 700, thenannandedat 500). boanddihave equal age and signup, andannandeddo too. They come out in input order (bobeforedi,annbeforeed), which theties keep input orderline checks using each user's input position.- The wrong order line sorts by age first and signup second. The last sort decides the final order, so it is sorted by signup descending (
bo,di,cy,ann,ed,flo) with ages mixed. The rule for chaining: the last pass is the primary key. - Score, latency, id: the comparator and the key
(-score, latency, id)giveb2, d4, a7, c1and the comparison printsTrue. Records with score 0.9 come first; among them latency 80 (b2,d4) before 120 (a7), and id breaks the tie betweenb2andd4. - Descending string: the numbers can be negated but a name cannot, so
sort_by_keyssorts by name descending first and by count ascending last:lee, kim(count 3) thenkay(count 5). - The 50000-user line shows the comparator, the two passes and the tuple key all return the same list, and counts the user-code calls: 714,542 comparator calls against 50,000 key calls. The last block runs 300 random inputs with heavy ties and compares every method with a reference that spells the rule out (age ascending, newest signup first, then input position). The comparator, the two passes, the tuple key and
sort_by_keysdiffer from it on 0 inputs; the three named mistakes (primary key sorted first,reverse=Trueon the whole sort, a boolean comparator) differ on 185, 246 and 221 of the 300.
Complexity
- Key-based sort: O(n log n) comparisons (done in C on the precomputed keys) plus n key computations, O(n) extra memory for the keys.
- Two passes: two O(n log n) sorts instead of one, and O(n) extra memory for the intermediate list.
- Comparator: still O(n log n) comparisons, but each one is a Python function call, so the constant is much larger.
- Stability is what makes option 2 (successive sorts) correct: the later pass must not disturb the order the earlier pass produced among equal keys. Options 1 and 3 are single sorts, where stability only decides ties. Python's
sortedis stable, andreverse=Truealso preserves the original order of equal elements (the reference comparison on tie-heavy inputs relies on it).
Edge cases and common mistakes
- Sorting the keys in the wrong order of passes (primary first).
- Negating a key that is not a number (strings) or that can be
None. - A comparator that contradicts itself (returns the same sign for
(x, y)and(y, x)) gives no meaningful order. A comparator that returns a boolean never reports "first goes first", so[3, 1, 2]comes back unchanged (printed above). Returninga - bworks in Python, but in C or Java, where the difference is a 32-bit integer, it can wrap around and flip the sign (printed above); return -1, 0 or 1 from comparisons instead. - Using
reverse=Trueon the whole sort when only one key should be descending flips the other key as well (thereverse=True on whole sortrow above differs from the reference on 246 of 300 inputs). - Missing tie-breaker: add a unique column (
id) as the last key when the output must be reproducible, for example for pagination. - Empty input and one-element input work with every method; equal timestamps keep input order because every method is stable.
Running the code
Save the program as multi_key_sort.py and run:
python multi_key_sort.py
Standard library only (dataclasses, functools, random); no install or config needed.
When is linear search a better choice than binary search? Cover array size, data layout, access cost, unsorted or streaming data, and give two concrete cases for each approach.
Sample Answer
The short answer
Choose linear search (look at items one by one, in order) when the data is small, unsorted, arrives as a stream, can only be walked in order, or the question is not an exact-match question. Choose binary search (repeatedly halve a sorted range) when the data is sorted, supports jumping to any position in constant time, and is searched many times. Binary search needs fewer element reads per search, but it has to pay for being sorted and indexable first, and that price is only worth paying under the right conditions.
The cost model
Everything below counts probes: the number of times an element is read and compared. The program counts probes, not seconds, because wall-clock time depends on the machine.
import bisect
import random
from functools import cmp_to_key
def linear_search(items, target):
"""Return (index or -1, element probes)."""
probes = 0
for i, x in enumerate(items):
probes += 1
if x == target:
return i, probes
return -1, probes
def binary_search(items, target):
lo, hi, probes = 0, len(items) - 1, 0
while lo <= hi:
mid = lo + (hi - lo) // 2
probes += 1
if items[mid] == target:
return mid, probes
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1, probes
# 1. Array size: probes for a target larger than every element (the worst case for both).
print("n linear probes binary probes")
for n in (1, 2, 4, 8, 64, 1000, 1_000_000):
data = list(range(n))
print(f"{n:<11}{linear_search(data, n)[1]:<15}{binary_search(data, n)[1]}")
# 2. Access cost: a singly linked list has no jump to the middle; reaching it means following next pointers.
class Node:
def __init__(self, value, nxt=None):
self.value, self.next = value, nxt
def build_list(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def linked_linear(head, target):
hops = 0
while head is not None:
if head.value == target:
return True, hops
head, hops = head.next, hops + 1
return False, hops
def linked_binary(head, n, target, log=None):
"""Binary search on a linked list: every probe walks forward from the start of the window."""
lo, hi, hops, probes = 0, n - 1, 0, 0
lo_node = head
while lo <= hi:
mid = lo + (hi - lo) // 2
probes += 1
node = lo_node
for _ in range(mid - lo):
node, hops = node.next, hops + 1
if node.value == target:
return True, hops, probes
if node.value < target:
lo, lo_node, hops = mid + 1, node.next, hops + 1
else:
hi = mid - 1
if log is not None:
log.append(hops)
return False, hops, probes
print("\nlinked list, n=1000, target absent:")
head = build_list(list(range(1000)))
print(" linear scan: pointer hops =", linked_linear(head, 1000)[1])
hop_log = []
found, hops, probes = linked_binary(head, 1000, 1000, hop_log)
print(f" binary search: pointer hops = {hops}, element comparisons = {probes}")
print(" hops added in each of the", len(hop_log), "rounds:", [b - a for a, b in zip([0] + hop_log, hop_log)])
# 3. Unsorted data: search once with a scan, or sort first and then binary search?
rng = random.Random(42)
n = 1000
data = rng.sample(range(10 ** 6), n)
sort_comparisons = 0
def counting_cmp(a, b):
global sort_comparisons
sort_comparisons += 1
return (a > b) - (a < b)
sorted_data = sorted(data, key=cmp_to_key(counting_cmp))
print(f"\nunsorted n={n}: sorting costs {sort_comparisons} comparisons")
queries = rng.sample(data, 200)
print("queries scan total probes sort + binary total probes")
for q in (1, 5, 10, 20, 50, 200):
scan = sum(linear_search(data, t)[1] for t in queries[:q])
binary = sort_comparisons + sum(binary_search(sorted_data, t)[1] for t in queries[:q])
print(f"{q:<9}{scan:<19}{binary}")
# 4. Streaming data: items arrive once and cannot be revisited or indexed.
stream = (rng.randrange(1000) for _ in range(10 ** 6))
consumed = 0
for value in stream:
consumed += 1
if value > 990:
break
print(f"\nstream: first value above 990 arrived as item {consumed}; memory used by the search is O(1)")
# 5. Compressed storage: sorted ids stored as variable-length deltas have no random access.
def encode_deltas(sorted_ids):
out, prev = bytearray(), 0
for v in sorted_ids:
delta = v - prev
prev = v
while delta >= 128:
out.append(128 | (delta & 127))
delta >>= 7
out.append(delta)
return bytes(out)
def scan_deltas(blob, target):
"""Decode left to right; the data is sorted, so stop as soon as the running value passes target."""
pos, value, shift, delta = 0, 0, 0, 0
while pos < len(blob):
b = blob[pos]
pos += 1
delta |= (b & 127) << shift
if b < 128:
value += delta
if value == target:
return True, pos
if value > target:
return False, pos
shift, delta = 0, 0
else:
shift += 7
return False, pos
def decode_all(blob):
values, value, shift, delta = [], 0, 0, 0
for b in blob:
delta |= (b & 127) << shift
if b < 128:
value += delta
values.append(value)
shift, delta = 0, 0
else:
shift += 7
return values
demo_ids = [5, 130, 300]
demo_deltas = [b - a for a, b in zip([0] + demo_ids, demo_ids)]
print("\ndelta encoding of", demo_ids, "-> deltas", demo_deltas, "-> bytes", list(encode_deltas(demo_ids)))
print(" decoded back:", decode_all(encode_deltas(demo_ids)), "; 170 is 128 + 42 then a second byte 1: 42 + 1 * 128 =", 42 + 1 * 128)
ids = sorted(rng.sample(range(10 ** 5), 1000))
blob = encode_deltas(ids)
print(f"\ncompressed ids: 1000 ids in {len(blob)} bytes")
print(" scan for ids[500] reads", scan_deltas(blob, ids[500])[1], "bytes ->", scan_deltas(blob, ids[500])[0])
print(" the middle byte has the value", blob[len(blob) // 2], "but ids[500] is", ids[500],
"(each stored number is a delta from the one before it)")
# 6. Approximate matching: the order of the keys says nothing about which keys are close.
def within_one_edit(a, b):
if abs(len(a) - len(b)) > 1:
return False
i = 0
while i < min(len(a), len(b)) and a[i] == b[i]:
i += 1
return a[i + 1:] == b[i + 1:] or a[i:] == b[i + 1:] or a[i + 1:] == b[i:]
for x, y in (("cat", "cut"), ("cat", "cart"), ("cart", "cat"), ("cat", "dog")):
print(f"within_one_edit({x!r}, {y!r}) =", within_one_edit(x, y))
words = sorted(["receive", "recipe", "reduce", "refer", "regard", "relax", "remote", "repeat", "result", "retail", "review", "reward"])
query = "xeceive"
near = [w for w in words if within_one_edit(query, w)]
print(f"\napproximate: scanning {len(words)} words for one edit away from {query!r} finds {near}")
print(" bisect would look near index", bisect.bisect_left(words, query), "but the match is at index", words.index("receive"))
The output below is the complete output of that program. In it, bisect is Python's standard-library module for binary search on a sorted list: bisect.bisect_left(words, x) returns the index where x would be inserted to keep the list sorted. Edit distance is the smallest number of single-character insertions, deletions or substitutions that turn one word into another.
n linear probes binary probes
1 1 1
2 2 2
4 4 3
8 8 4
64 64 7
1000 1000 10
1000000 1000000 20
linked list, n=1000, target absent:
linear scan: pointer hops = 1000
binary search: pointer hops = 1000, element comparisons = 10
hops added in each of the 10 rounds: [500, 250, 125, 63, 31, 16, 8, 4, 2, 1]
unsorted n=1000: sorting costs 8645 comparisons
queries scan total probes sort + binary total probes
1 359 8655
5 2126 8691
10 4622 8738
20 8589 8827
50 24815 9084
200 102564 10439
stream: first value above 990 arrived as item 21; memory used by the search is O(1)
delta encoding of [5, 130, 300] -> deltas [5, 125, 170] -> bytes [5, 125, 170, 1]
decoded back: [5, 130, 300] ; 170 is 128 + 42 then a second byte 1: 42 + 1 * 128 = 170
compressed ids: 1000 ids in 1284 bytes
scan for ids[500] reads 645 bytes -> True
the middle byte has the value 78 but ids[500] is 52487 (each stored number is a delta from the one before it)
within_one_edit('cat', 'cut') = True
within_one_edit('cat', 'cart') = True
within_one_edit('cart', 'cat') = True
within_one_edit('cat', 'dog') = False
approximate: scanning 12 words for one edit away from 'xeceive' finds ['receive']
bisect would look near index 12 but the match is at index 0
1. Array size
For a target larger than every element (the worst case for both), the table shows linear search reading all n items and binary search reading about log2 n: 1 and 1 at n = 1, 4 and 3 at n = 4, 8 and 4 at n = 8, 1000 and 10 at n = 1000, and 1,000,000 and 20 at n = 1,000,000. Up to n = 8 the difference is at most 4 reads (8 against 4), and each binary probe also carries bookkeeping (computing mid, branching on the result) while a scan is a simple loop, so on arrays that small the probe count alone does not decide the winner; a real choice at that size should be settled by the other factors below, and by measuring if it matters. As n grows the gap in reads grows with it (64 reads against 7 at n = 64, 1000 against 10 at n = 1000) until it dominates.
2. Data layout and access cost
Binary search assumes random access: reading item mid costs the same wherever mid is. That holds for an array. It fails in two ways:
- A linked list has no jump. To read the middle node you follow
nextpointers from the start of the window. In the program, binary search on a 1000-node list needs 10 element comparisons but still follows 1000 pointers, the same number as the plain scan, because the walks to the successive midpoints add up to roughly n. In each round the code walks from the start of the current window to its middle, then one more step tomid + 1, which becomes the start of the next window. The window halves each round, so the walks halve too; the program prints the hops added in each of the 10 rounds (the list in the output), and they add up to the 1000 shown. Fewer comparisons, no fewer pointer hops. So on a linked list, scan it, or build an index. - Compressed or variable-length storage (each item takes a different number of bytes, so the start of item 500 cannot be computed). The program stores 1000 sorted ids as byte deltas (delta encoding: each stored number is the gap from the previous id, using one or two bytes). Each byte carries 7 bits of the gap in its low bits (
delta & 127), and its top bit is set (128 | ...) when another byte follows;delta >>= 7drops the 7 bits already written. To decode,(b & 127) << shiftputs each 7-bit piece back in place. The small printed example makes this concrete: ids 5, 130, 300 have gaps 5, 125 and 170; 5 and 125 fit in one byte each, and 170 does not, so it is written as 170 (the low 7 bits, 42, plus the top bit 128) followed by the byte 1, which decodes as 42 + 1 x 128 = 170. An id can only be recovered by decoding every delta before it, so there is no way to jump to element 500: the middle byte of the blob has the value 78, which is only a fragment of one gap, while the id at position 500 is 52,487. Scanning with an early stop is what works, and here it read 645 of the 1,284 bytes to findids[500]. Binary search becomes possible again if you keep a small side index holding every k-th id and its byte offset (a skip index), then scan only inside one block.
Contiguous arrays (items stored back to back in memory) also tend to be friendly to a scan: the processor's cache, a small fast memory that loads a whole neighbourhood of addresses at once, already holds the next element, while binary search jumps across memory and misses the cache more often. That cache locality makes small arrays a better fit for scanning than the probe counts alone suggest.
3. Unsorted data
Binary search requires sorted data, and sorting costs O(n log n). The program sorts 1000 random distinct numbers with a counting comparator: 8,645 comparisons. Then it compares total probes for q queries: scanning costs 8,589 probes for 20 queries against 8,827 for sort-plus-binary (the scan is still ahead), and 24,815 against 9,084 for 50 queries (sorting has paid off). So for this array the break-even sits between 20 and 50 queries. If you search once, or a few times, scan. If you search the same data thousands of times, sort once (or keep a hash index, which is a separate alternative to both).
4. Streaming data
A stream delivers each item once and cannot be indexed or revisited, so a binary search has nothing to probe. A scan processes each item as it arrives, stops at the first match (item 21 in the program's stream) and keeps O(1) memory. Sorting a stream first means holding all of it in memory.
Two concrete cases for each approach
Linear search is the right tool when:
- You look up one value in a short unsorted list a single time, for example checking whether a feature name appears in a 20-entry configuration list.
- You read a live log stream for the first line matching a condition, so each line is seen once and in arrival order.
Binary search is the right tool when:
- A sorted array of ten million user ids is loaded once and queried millions of times, so the one-time cost of keeping it sorted is spread across the queries.
- You need the position of a timestamp in a sorted array of events, for example the first event at or after a given time (the boundary of a time range), where an exact match is not even required.
Other cases where linear search wins
- Linked lists: described above (section 2).
- Compressed storage: described above (section 2).
- Approximate matching. Binary search needs a total order (any two keys can be compared and the sorted order is consistent) in which "closer" means "nearby in the array". Edit-distance matching has no such order. The function
within_one_editskips the shared leading characters, then checks the three ways one edit can fix the rest: replace one character (a[i + 1:] == b[i + 1:]), delete one fromb(a[i:] == b[i + 1:]) or delete one froma(a[i + 1:] == b[i:]); the four printedwithin_one_editlines show a substitution, an insertion, a deletion and a clear miss. The program scans 12 sorted words for anything one edit away fromxeceive(a typo ofreceivein its first letter) and findsreceive;bisecton the sorted words would land at index 12, while the match is at index 0, because alphabetical order says nothing about similarity of the rest of the word. For approximate matches use a scan with a distance function, or a structure built for it (such as a BK-tree, a tree whose branches are labelled by edit distance so that a query can skip parts of the tree), not a binary search.
How to decide
- Is it sorted, or will you sort it once and query it many times? If no, scan.
- Can you read any position in constant time (an array, not a list or a decoded stream)? If no, scan, or add an index.
- Is the query an exact match or a boundary on the same sort order? If it is fuzzy or by another key, scan or use another structure.
- Is n large enough that log2 n matters (hundreds or more)? If n is tiny, either works; prefer the simpler scan.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python search_cost_demo.py
Save the program as search_cost_demo.py. It uses only the standard library, uses fixed seeds, and the output above is from Python 3.12.
Write a Java method to find the first (leftmost) occurrence of target in a sorted integer array that may contain duplicates. Signature: public static int firstOccurrence(int[] arr, int target). Explain loop invariants and boundary conditions to ensure correctness.
Sample Answer
Direct answer
To find the leftmost occurrence, do not stop when you see the target. Treat the problem as "find the first index whose value is greater than or equal to the target" (a lower bound), then check whether that index really holds the target. Equal values at mid push the window left (hi = mid), smaller values push it right (lo = mid + 1). If the lower-bound index is past the end or holds a different value, return -1. Time O(log n), space O(1).
The idea in plain words
In [1, 2, 2, 2, 2, 3, ...], the ordinary binary search returns as soon as it sees any 2, which could be index 2, 3 or 4. The first 2 sits at index 1, exactly at the boundary where values stop being "less than 2" and start being "at least 2". Because the array is sorted, all "less than target" values come first and all "at least target" values come after, so finding the leftmost target means finding that boundary.
Marking each value as "less than the target or not" makes the boundary visible. This small program prints the marks for the trace array and target 2:
arr = [1, 2, 2, 2, 2, 3, 5, 5, 8]
target = 2
print("index :", " ".join(f"{i:2d}" for i in range(len(arr))))
print("value :", " ".join(f"{v:2d}" for v in arr))
print("< 2 ? :", " ".join(" Y" if v < target else " N" for v in arr))
first_n = next(i for i, v in enumerate(arr) if v >= target)
print("the Y run ends before index", first_n, "so the first value >= 2 is at index", first_n)
Output (python:3.12):
index : 0 1 2 3 4 5 6 7 8
value : 1 2 2 2 2 3 5 5 8
< 2 ? : Y N N N N N N N N
the Y run ends before index 1 so the first value >= 2 is at index 1
The Ys (too small) come first and the Ns (big enough) after them, so the search is looking for the place where the Ys stop.
Brute force
A linear scan from index 0 returns the first match in O(n). Binary search with a walk to the left after finding a match is O(n) as well (all-equal input walks the whole array). The boundary search stays O(log n) even then.
Approach and invariant
Use a half-open window [lo, hi): lo is included, hi is not. Start with lo = 0 and hi = arr.length, so an empty array gives an empty window and the loop never runs.
Loop invariant, in words: every index to the left of lo holds a value smaller than the target, and every index at or after hi holds a value at least as big as the target. Only the positions between lo and hi are undecided. Each step keeps this true:
- If
arr[mid] < target, thenmidand everything left of it are too small, solo = mid + 1. - Otherwise
arr[mid] >= target, somidcould still be the first occurrence and must stay inside the window:hi = mid(notmid - 1).
The window shrinks every round (mid is always inside it, and either bound moves past or onto mid while the window is non-empty), so the loop ends with lo == hi, the boundary. By the invariant, lo is the first index whose value is at least the target, so the target is present exactly when lo < arr.length and arr[lo] == target.
Code
The mid is lo + (hi - lo) / 2, which cannot overflow a 32-bit int (unlike (lo + hi) / 2 when both are near 2^30 or more). The extra overload with trace prints lo, hi and mid so the steps can be followed; the required method is the two-argument one. Notes for readers coming from Python: int[] is Java's fixed-size array of 32-bit integers; two methods may share a name if their parameter lists differ (an overload, here the two-argument public method and the three-argument one with trace); AssertionError is the exception thrown by the program's own check when a result is wrong; and / between two Java int values is integer division that drops the fraction (7 / 2 is 3), so lo + (hi - lo) / 2 behaves like Python's // for the non-negative values used here. The main method runs the edge cases and compares against a linear scan on 5000 random sorted arrays (seed 42).
import java.util.Arrays;
import java.util.Random;
public class FirstOccurrence {
// Invariant: every index < lo holds a value < target,
// every index >= hi holds a value >= target.
// The window [lo, hi) is the only part not yet decided.
public static int firstOccurrence(int[] arr, int target) {
return firstOccurrence(arr, target, false);
}
static int firstOccurrence(int[] arr, int target, boolean trace) {
int lo = 0;
int hi = arr.length; // exclusive upper end
while (lo < hi) {
int mid = lo + (hi - lo) / 2; // no int overflow
if (trace) {
System.out.println(" lo=" + lo + " hi=" + hi + " mid=" + mid + " arr[mid]=" + arr[mid]);
}
if (arr[mid] < target) {
lo = mid + 1; // mid and everything left of it is too small
} else {
hi = mid; // mid could be the answer, keep it in the window
}
}
// lo == hi: the first index whose value is >= target
return (lo < arr.length && arr[lo] == target) ? lo : -1;
}
static int linearScan(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 2, 2, 2, 3, 5, 5, 8};
System.out.println("arr = " + Arrays.toString(arr));
System.out.println("target 2:");
System.out.println("result " + firstOccurrence(arr, 2, true));
System.out.println("target 4 (absent):");
System.out.println("result " + firstOccurrence(arr, 4, true));
System.out.println("empty array: " + firstOccurrence(new int[]{}, 7));
System.out.println("one element hit: " + firstOccurrence(new int[]{7}, 7));
System.out.println("one element miss: " + firstOccurrence(new int[]{7}, 3));
System.out.println("all equal: " + firstOccurrence(new int[]{4, 4, 4, 4, 4}, 4));
System.out.println("target at left end: " + firstOccurrence(arr, 1));
System.out.println("target at right end: " + firstOccurrence(arr, 8));
System.out.println("smaller than all: " + firstOccurrence(arr, 0));
System.out.println("larger than all: " + firstOccurrence(arr, 99));
Random rng = new Random(42);
for (int round = 0; round < 5000; round++) {
int[] a = new int[rng.nextInt(12)];
for (int i = 0; i < a.length; i++) a[i] = rng.nextInt(7);
Arrays.sort(a);
int t = rng.nextInt(9) - 1;
if (firstOccurrence(a, t) != linearScan(a, t)) {
throw new AssertionError(Arrays.toString(a) + " target " + t);
}
}
System.out.println("5000 random checks against a linear scan passed");
}
}
Run in an eclipse-temurin:21-jdk container, it prints:
arr = [1, 2, 2, 2, 2, 3, 5, 5, 8]
target 2:
lo=0 hi=9 mid=4 arr[mid]=2
lo=0 hi=4 mid=2 arr[mid]=2
lo=0 hi=2 mid=1 arr[mid]=2
lo=0 hi=1 mid=0 arr[mid]=1
result 1
target 4 (absent):
lo=0 hi=9 mid=4 arr[mid]=2
lo=5 hi=9 mid=7 arr[mid]=5
lo=5 hi=7 mid=6 arr[mid]=5
lo=5 hi=6 mid=5 arr[mid]=3
result -1
empty array: -1
one element hit: 0
one element miss: -1
all equal: 0
target at left end: 0
target at right end: 8
smaller than all: -1
larger than all: -1
5000 random checks against a linear scan passed
Worked trace
For target 2 in [1, 2, 2, 2, 2, 3, 5, 5, 8]: window [0, 9), mid 4 holds 2 (not smaller), so hi becomes 4. Window [0, 4), mid 2 holds 2, hi becomes 2. Window [0, 2), mid 1 holds 2, hi becomes 1. Window [0, 1), mid 0 holds 1 (smaller), so lo becomes 1. Now lo == hi == 1, arr[1] is 2, so the answer is 1 (the leftmost 2). For the absent target 4: mid 4 holds 2 (smaller), lo becomes 5; mid 7 holds 5, hi becomes 7; mid 6 holds 5, hi becomes 6; mid 5 holds 3 (smaller), lo becomes 6. Then lo == hi == 6, arr[6] is 5, which is not 4, so the method returns -1.
Complexity
Time O(log n): each round halves the window hi - lo, so at most about log2(n) + 1 rounds, plus one final array read. Space O(1). It is iterative, so there is no stack depth.
Edge cases and common mistakes
- Empty array: the window is empty, the final check fails the
lo < arr.lengthtest, and the method returns -1 (shown in the run). - One element: either the lone value matches (index 0) or it does not (-1).
- All-equal array: every
midsatisfiesarr[mid] >= target, sohikeeps moving left to 0 and the answer is 0, in O(log n). - Target absent, below the first element or above the last: the boundary lands at 0 or at
arr.length, and the final check returns -1 (the last case is whylo < arr.lengthmust come beforearr[lo], to avoid an out-of-bounds read). - Mistake:
hi = mid - 1on a match throws away a possible answer (whenmidis the first occurrence), and with a closed[lo, hi]window andhi = midthe loop can stop making progress; keep the window half-open and the update pairlo = mid + 1/hi = mid. - Mistake: returning immediately on
arr[mid] == target, which returns any occurrence rather than the first. - Mistake: forgetting the final equality check, which would return the boundary index for absent targets.
Running the code
Java 21 (JDK).
Save the listing as FirstOccurrence.java, then:
javac FirstOccurrence.java && java FirstOccurrence
Describe the classic First Bad Version problem where versions are numbered and you have an API isBadVersion(version) that returns a boolean with monotonic behavior. Implement a solution that finds the earliest bad version using O(log n) API calls. Discuss off-by-one pitfalls and test cases.
Sample Answer
The idea in plain words
Versions 1 to n were released in order, and once a version is bad every later one is bad too (the API is monotonic: its answers go False, False, ..., True, True). You want the first True. The list of answers is a sorted yes/no sequence, so you can binary search it: ask about the middle version, and the answer tells you which half to throw away. Each API call is expensive in the story (it builds and tests a release), so the goal is the fewest calls, not the fewest lines.
The brute force asks about version 1, 2, 3, ... and makes up to n calls. Binary search makes at most ceil(log2 n) calls. Here log2 n is the number of times n can be halved before reaching 1 (log2 8 = 3), and ceil rounds up to a whole number of calls. For n = 10 each probe leaves at most the larger half, so the window shrinks 10, 5, 3, 2, 1: four calls, and log2 10 = 3.32 rounds up to 4 (the first printed line shows these sizes).
The approach
Keep a window lo..hi with this invariant, in words: the first bad version is somewhere in lo..hi, both ends included. The window starts as 1..n, which is valid when version n is bad (the problem's premise: a precondition, meaning a fact the caller must guarantee before calling, so that the search is allowed to assume it). Probe mid:
- If
midis bad, then the first bad version ismiditself or earlier, sohi = mid. You cannot writemid - 1, becausemidmight be the answer. - If
midis good, then every version up tomidis good, solo = mid + 1.
The loop runs while lo < hi. When lo == hi the window has one version in it and the invariant says that is the first bad one, so no further call is needed. Each step shrinks the window (mid < hi, and mid + 1 > lo), so it terminates.
The code
from math import ceil, log2
def first_bad_version(n, is_bad_version):
"""Smallest v in 1..n with is_bad_version(v) True. Assumes version n is bad."""
lo, hi = 1, n # invariant: the first bad version is in lo..hi
while lo < hi:
mid = lo + (hi - lo) // 2
if is_bad_version(mid):
hi = mid # mid is bad, so the first bad is mid or earlier
else:
lo = mid + 1 # mid is good, so every version up to mid is good
return lo
def first_bad_or_none(n, is_bad_version):
"""Same search, but returns None when no version is bad (costs one extra API call)."""
if n < 1 or not is_bad_version(n):
return None
return first_bad_version(n, is_bad_version)
class Api:
"""Fake API: versions first_bad..n are bad. Records every call."""
def __init__(self, first_bad):
self.first_bad, self.calls = first_bad, []
def __call__(self, version):
self.calls.append(version)
return version >= self.first_bad
def mutant_first_bad(n, is_bad_version):
"""Wrong on purpose: 'hi = mid - 1' skips the answer when mid is the first bad version."""
lo, hi = 1, n
while lo < hi:
mid = lo + (hi - lo) // 2
if is_bad_version(mid):
hi = mid - 1
else:
lo = mid + 1
return lo
size, sizes = 10, [10]
while size > 1:
size = (size + 1) // 2 # the larger half can remain, so round up
sizes.append(size)
print("window sizes for n=10 when halving and rounding up:", sizes, "->", len(sizes) - 1,
"halvings; log2(10) =", round(log2(10), 2), "and ceil =", ceil(log2(10)))
api = Api(first_bad=7)
print("n=10, first bad 7 ->", first_bad_version(10, api), "calls:", api.calls)
print("\nn worst calls allowed ceil(log2 n)")
for n in (1, 2, 3, 5, 8, 100, 1000):
worst = 0
for first in range(1, n + 1):
api = Api(first)
assert first_bad_version(n, api) == first
assert len(set(api.calls)) == len(api.calls) # never asks about the same version twice
worst = max(worst, len(api.calls))
print(f"{n:<6}{worst:<13}{ceil(log2(n))}")
checked = 0
for n in range(1, 130):
for first in range(1, n + 1):
api = Api(first)
assert first_bad_version(n, api) == first and len(api.calls) <= ceil(log2(n))
checked += 1
print("\nexhaustive check passed for", checked, "(n, first bad) pairs with n up to 129")
n = 2 ** 31 - 1
api = Api(first_bad=n - 3)
print("n = 2**31 - 1, first bad", n - 3, "->", first_bad_version(n, api), "in", len(api.calls), "calls")
api = Api(first_bad=1)
print("everything bad ->", first_bad_version(10, api), "after", len(api.calls), "calls")
api = Api(first_bad=11)
print("nothing bad (first_bad_version, wrong precondition) ->", first_bad_version(10, api))
api = Api(first_bad=11)
print("nothing bad (first_bad_or_none) ->", first_bad_or_none(10, api), "after", len(api.calls), "call")
caught = 0
for n in range(1, 30):
for first in range(1, n + 1):
caught += mutant_first_bad(n, Api(first)) != first
print("mutant with hi = mid - 1 is wrong on", caught, "pairs")
for n in range(1, 30):
first = next((f for f in range(1, n + 1) if mutant_first_bad(n, Api(f)) != f), None)
if first is not None:
api = Api(first)
print(f"smallest failing input: n={n}, first bad {first}: mutant returns {mutant_first_bad(n, api)}, "
f"probes {api.calls}")
break
The output below is the complete output of that program.
window sizes for n=10 when halving and rounding up: [10, 5, 3, 2, 1] -> 4 halvings; log2(10) = 3.32 and ceil = 4
n=10, first bad 7 -> 7 calls: [5, 8, 7, 6]
n worst calls allowed ceil(log2 n)
1 0 0
2 1 1
3 2 2
5 3 3
8 3 3
100 7 7
1000 10 10
exhaustive check passed for 8385 (n, first bad) pairs with n up to 129
n = 2**31 - 1, first bad 2147483644 -> 2147483644 in 31 calls
everything bad -> 1 after 4 calls
nothing bad (first_bad_version, wrong precondition) -> 10
nothing bad (first_bad_or_none) -> None after 1 call
mutant with hi = mid - 1 is wrong on 161 pairs
smallest failing input: n=3, first bad 2: mutant returns 1, probes [2]
Reading the trace for n = 10, first bad version 7
The calls were 5, 8, 7, 6:
lo=1, hi=10, probe 5: good, solo=6.lo=6, hi=10, probe 8: bad, sohi=8.lo=6, hi=8, probe 7: bad, sohi=7.lo=6, hi=7, probe 6: good, solo=7.
Now lo == hi == 7 and the function returns 7 after 4 calls, which equals ceil(log2 10).
Complexity
- API calls: at most ceil(log2 n). The table above is measured from the code: the worst case over every possible first-bad position is 0, 1, 2, 3, 3, 7 and 10 calls for n = 1, 2, 3, 5, 8, 100 and 1000, equal to ceil(log2 n) each time. For n = 2^31 - 1 it took 31 calls. The program also asserts that no version is ever probed twice.
- Time and space: O(log n) time and O(1) extra space, because it is a loop with two integers.
Edge cases, tests and pitfalls
- One version (n = 1): the loop never runs and the answer is 1 with zero calls, relying on the premise that it is bad.
- First bad is version 1, or the last version: both are in the exhaustive check (every
(n, first bad)pair for n up to 129, 8,385 pairs, each also asserting the call count). - No bad version at all:
first_bad_versionassumes the premise and returns n (printed above forfirst_bad=11, which is the wrong answer to the wrong question). If the caller cannot guarantee a bad version,first_bad_or_nonefirst asks about version n, one extra call, and returnsNone. - Large n:
lo + (hi - lo) // 2avoids thelo + hisum that overflows a 32-bit signed integer when n is near 2^31 - 1. Python would not overflow, but the habit carries over to C++ and Java. - Off-by-one traps:
hi = mid - 1(the shipped mutant, wrong on 161 of the 435 pairs with n from 1 to 29; the last printed line shows the smallest failing input, where the probe lands exactly on the first bad version, the mutant then discards it and returns the wrong version), looping onlo <= hiwhile settinghi = mid(never ends whenlo == hi), and returninglo - 1orhi + 1. - Never ask about the same version twice. When each call is slow, a repeated probe is wasted money; the loop never repeats one, and the program asserts it for every case in the table.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python first_bad_version_demo.py
Save the program as first_bad_version_demo.py. It uses only the standard library, and the output above is from Python 3.12.
Explain what 'stable sort' and 'in-place sort' mean with concrete examples. Given the list of tuples [(name, age)]: [('alice', 30), ('bob', 25), ('carol', 30)], show a stable and an unstable sort by age and explain why stability matters in multi-key sorting.
Sample Answer
The idea in plain words
- A sort is stable if records with equal keys come out in the same relative order they went in. Sorting
[('alice', 30), ('bob', 25), ('carol', 30)]by age, alice and carol tie at 30. A stable sort must put alice before carol, because alice came first. An unstable sort is allowed to swap them. - A sort is in place if it rearranges the list it was given using only a small, fixed amount of extra memory (a few variables, or a stack of about log n frames), instead of building a second list of the same size. In Python,
list.sort()changes the list and returnsNone;sorted()builds and returns a new list.
The two properties are independent. Insertion sort is stable and in place. Merge sort (array version) is stable but not in place. Quicksort and heapsort are in place but not stable. Python's list.sort is stable by documentation (the line from its docstring in the output below says so).
Terms used below: quicksort picks one row as the pivot and partitions the list, which means moving rows smaller than the pivot to its left and the others to its right, then repeats on each side. Heapsort arranges the rows into a heap (a structure whose largest row sits at the front), then repeatedly swaps the front row to the end. Timsort is the merge-and-insertion hybrid that Python's built-in sort uses. A tie-breaker is an extra key added at the end of the sort key so that rows with equal main keys still have one fixed order.
A stable and an unstable sort of the example
The program sorts the three tuples by age three ways: with sorted (stable), with a quicksort that uses the last element as the pivot (unstable), and with an in-place insertion sort (stable). Then it shows the in-place versus new-list difference, multi-key sorting, and a pagination example.
import random
def quicksort_by_age(rows, trace=False):
"""In-place quicksort, last element as pivot, strict < in the partition. Not stable."""
def sort(lo, hi):
if lo >= hi:
return
pivot, i = rows[hi][1], lo
for j in range(lo, hi):
if rows[j][1] < pivot:
rows[i], rows[j] = rows[j], rows[i]
if trace:
print(f" swap slots {i} and {j} (a smaller-than-pivot row moves left):", [r[0] for r in rows])
i += 1
rows[i], rows[hi] = rows[hi], rows[i]
if trace:
print(f" swap pivot into slot {i}:", [r[0] for r in rows])
sort(lo, i - 1)
sort(i + 1, hi)
sort(0, len(rows) - 1)
def insertion_by_age(rows):
"""In-place insertion sort. Stable: shifts only while the left item is strictly greater."""
for i in range(1, len(rows)):
item, j = rows[i], i - 1
while j >= 0 and rows[j][1] > item[1]:
rows[j + 1] = rows[j]
j -= 1
rows[j + 1] = item
people = [("alice", 30), ("bob", 25), ("carol", 30)]
stable = sorted(people, key=lambda p: p[1])
print("stable (sorted by age):", stable)
unstable = list(people)
print("quicksort steps (pivot = last row, carol, age 30):")
quicksort_by_age(unstable, trace=True)
print("unstable (quicksort) :", unstable)
in_place = list(people)
insertion_by_age(in_place)
print("insertion sort, in place:", in_place)
print("list.sort says:", " ".join(list.sort.__doc__.split("\n\n")[1].split()))
# in-place vs new list
original = list(people)
returned = original.sort(key=lambda p: p[1])
print("list.sort() returns", returned, "and changed the list itself:", original)
copy = sorted(people, key=lambda p: p[1])
print("sorted() left the input alone:", people, "and built a new list:", copy)
# Multi-key sorting with successive stable sorts: department ascending, then age descending.
staff = [("dana", "ops", 41), ("eli", "dev", 30), ("fay", "ops", 41), ("gus", "dev", 35), ("hal", "ops", 29)]
step1 = sorted(staff, key=lambda r: r[2], reverse=True) # secondary key first
print("\nafter pass 1 (age desc):", [r[0] for r in step1])
step2 = sorted(step1, key=lambda r: r[1]) # primary key last
print("after pass 2 (dept asc):", [r[0] for r in step2])
print("fay and dana tie on both keys and keep input order:", step2.index(staff[0]) < step2.index(staff[2]))
# Paginated results: sorting only by age, with ties returned in an unspecified order.
users = [(f"user{i}", 20 + i % 3) for i in range(9)]
def fetch_page(page, size, seed):
rows = list(users)
random.Random(seed).shuffle(rows) # stands in for a store that orders ties arbitrarily
rows.sort(key=lambda r: r[1]) # stable, but the incoming tie order differs per request
return rows[page * size:(page + 1) * size]
page0 = fetch_page(0, 4, seed=1)
page1 = fetch_page(1, 4, seed=2)
page2 = fetch_page(2, 4, seed=3)
seen = [r[0] for r in page0 + page1 + page2]
print("\nage-only paging, rows seen:", len(seen), "distinct:", len(set(seen)))
missing = sorted(set(u[0] for u in users) - set(seen))
print("never shown:", missing)
def fetch_page_fixed(page, size, seed):
rows = list(users)
random.Random(seed).shuffle(rows)
rows.sort(key=lambda r: (r[1], r[0])) # tie-breaker: the unique name
return rows[page * size:(page + 1) * size]
seen = [r[0] for p, s in ((0, 1), (1, 2), (2, 3)) for r in fetch_page_fixed(p, 4, s)]
print("with (age, name) key, rows seen:", len(seen), "distinct:", len(set(seen)))
Run in a python:3.12 container (Python 3.12), it prints:
stable (sorted by age): [('bob', 25), ('alice', 30), ('carol', 30)]
quicksort steps (pivot = last row, carol, age 30):
swap slots 0 and 1 (a smaller-than-pivot row moves left): ['bob', 'alice', 'carol']
swap pivot into slot 1: ['bob', 'carol', 'alice']
unstable (quicksort) : [('bob', 25), ('carol', 30), ('alice', 30)]
insertion sort, in place: [('bob', 25), ('alice', 30), ('carol', 30)]
list.sort says: The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
list.sort() returns None and changed the list itself: [('bob', 25), ('alice', 30), ('carol', 30)]
sorted() left the input alone: [('alice', 30), ('bob', 25), ('carol', 30)] and built a new list: [('bob', 25), ('alice', 30), ('carol', 30)]
after pass 1 (age desc): ['dana', 'fay', 'gus', 'eli', 'hal']
after pass 2 (dept asc): ['gus', 'eli', 'dana', 'fay', 'hal']
fay and dana tie on both keys and keep input order: True
age-only paging, rows seen: 9 distinct: 7
never shown: ['user4', 'user8']
with (age, name) key, rows seen: 9 distinct: 9
Reading the output
- Stable:
[bob 25, alice 30, carol 30]. alice stays ahead of carol. - Unstable (the quicksort):
[bob 25, carol 30, alice 30]. The printed steps show it: the pivot is carol (age 30). The partition step swaps alice with bob (bob is smaller than the pivot), givingbob, alice, carol, and then the final swap that puts the pivot in place exchanges carol (slot 2) with alice (slot 1), givingbob, carol, alice. Alice has jumped over carol. Nothing is wrong with the result by age; only the order of equal keys changed. This is the kind of reordering swaps across a distance produce; it is not random. - Insertion sort only shifts elements that are strictly larger, so alice and carol never pass each other: stable and in place.
- In place versus new list:
list.sort(key=...)returnedNoneand the original list changed;sorted(...)left the input alone and built a new list. - The stability of Python's built-in sort is stated in its docstring. The program prints it from
list.sort.__doc__on Python 3.12: "The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained)."
Why stability matters: multi-key sorting
To sort by department ascending and, inside a department, by age descending, sort in successive passes starting with the least important key: first by age descending, then by department ascending. Because the second pass is stable, people in the same department keep the age order from the first pass. In the output, pass 1 gives dana, fay, gus, eli, hal (age 41, 41, 35, 30, 29) and pass 2 groups by department: gus, eli (dev), then dana, fay, hal (ops), each group still in age-descending order. dana and fay tie on both keys and stay in input order. If the second pass were unstable, the age order inside each department could be scrambled. Doing the passes in the other order (primary first) would let the last pass override it; the last sort always wins.
Stability and paginated results
Pagination means fetching a long sorted result in pages (rows 0 to 3, then 4 to 7, and so on), one request per page. A database or search store is allowed to return rows with equal sort keys in any order, and that order can differ from one request to the next. Sorting only by age in such a store, each page request can see ties in a different order, so a tied row can slip across a page boundary and be shown twice or never. The simulation shuffles the rows per request (to stand in for that), sorts by age, and takes pages of 4 rows: across three pages 9 rows are shown but only 7 distinct, and user4 and user8 are never shown. Adding a unique tie-breaker to the sort key, (age, name), makes the order total and deterministic: all 9 distinct rows appear exactly once. The rule: for any paginated or reproducible ordering, end the key with a unique column such as an id. A stable algorithm alone does not help when the input order itself changes between requests.
Complexity and when each property costs something
- Stable sorting in the standard library costs nothing extra to use: Python's sort is O(n log n) worst case and stable.
- Stable algorithms: insertion, bubble, merge, Timsort, counting sort. Unstable by default: selection (the swap version), quicksort, heapsort. Any unstable sort can be made stable by adding the original index as a final tie-breaker in the key, at the cost of O(n) extra memory for the indexes.
- In place means O(1) or O(log n) extra memory: insertion, selection, bubble, heap, and quicksort are in place; merge sort on arrays uses O(n) extra, so it is not.
Edge cases and common mistakes
- Stability only matters when keys can tie and the tied records can be told apart; sorting plain integers, a stable and an unstable result are the same list.
- Confusing "in place" with "stable": they are independent properties.
- Calling a sort in place when it uses an auxiliary array of size n.
- Assuming the sort a database or another library uses is stable; if you need a tie order, put it in the sort key.
- Doing the multi-key passes in the wrong order, or using
reverse=Trueand expecting ties to flip: Python'sreverse=Truekeeps equal elements in their original order, so it preserves stability.
Running the code
Save the program as stable_sort_demo.py and run:
python stable_sort_demo.py
Standard library only (random); no install or config needed.
Unlock Full Question Bank
Get access to all 16 Sorting and Searching Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.