Write down the middle entry of every interval binary search can ever look at, and you get a tree. For N = 2k โ 1 entries it is perfectly balanced: the interval sizes go 2kโ1, 2kโ1โ1, โฆ, 3, 1. Every search miss is a top-to-bottom path: k levels, k compares, and k = lg(N+1) ~ lg N.
1 ยท Build the tree one level at a time
Each level holds the middles of the intervals left over by the level above. Removing the middle from an interval of size 2k โ 1 leaves two halves of size (2k โ 2)/2 = 2kโ1 โ 1: the same form again, one power lower. The array below the tree shows the intervals of the newest level.
k (N = 2แต โ 1)
level = call
intervals
size of each
formula
2 ยท Every search is a path from the top
A search starts at the root (the middle of the whole array) and moves one level down per compare. A hit stops at the node holding the key. A miss runs off the bottom into an empty interval: it always costs all k levels.
Search
10
compares (this search)โ
every missโ
average hitโ
lg Nโ
3 ยท The numbers: lg N versus N
Exact compare counts for N = 2k โ 1. A miss costs k = lg(N+1). A random hit costs a little less, because it can stop above the bottom level — but half of all nodes sit on the bottom level, so the average stays close to k โ 1. Sequential search for comparison.
k
N = 2แต โ 1
lg N
binary: miss
binary: avg hit
sequential: avg hit
sequential: miss
For other N the halves differ by at most one entry, the tree is no longer perfect, and the worst case is โlg Nโ + 1 compares (the number of bits of N). Both formulas agree at N = 2k โ 1: โlg 15โ + 1 = 3 + 1 = 4 = lg 16. The book derives the same ~lg N from the recurrence T(n) = T(n/2) + 1 (p. 535).
Companion to the binary-search session (lecture slides 1–19, book ยง4.2, p. 535 and Program 4.2.3, p. 539). Before: binary search arithmetic (slide 5) and the recursion trace (slide 10).