Binary Search
Looking for a value in an unsorted list means checking every element: O(n). In a sorted list you can do much better. Look at the middle: if the value there is too small, the answer is in the right half; otherwise it's in the left half. Each look throws away half of what's left, so a million elements need only about 20 looks: O(log n).
sort.Search
Writing binary search by hand is famous for off-by-one bugs. Go's sort.Search does it for you, and it's more general than "find this value":
i := sort.Search(n, func(i int) bool { return xs[i] >= 50 })
sort.Search(n, f) returns the smallest i in [0, n) for which f(i) is true, or n if there is none. The one rule: f must be false, false, ..., then true, true, ... and never switch back. For a sorted slice, xs[i] >= target has exactly that shape.
So the line above finds the first value that is at least 50. To check whether 50 itself is there, test i < len(xs) && xs[i] == 50. For the common case, slices.BinarySearch(xs, 50) returns both the position and whether it was found.
Counting a range
How many values lie between lo and hi? Find where the values >= lo start, and where the values >= hi+1 start. Everything in between is in the range:
count := firstAtLeast(xs, hi+1) - firstAtLeast(xs, lo)
Two searches, O(log n), no matter how many values are in the range.
Searching for the answer
sort.Search doesn't need a slice at all, only a yes/no question that switches from no to yes once. That makes it useful when the answer itself is a number you could search for: "what's the smallest size that's big enough?" If you can check one candidate quickly, you can binary search over all candidates:
side := sort.Search(2_000_000_000, func(s int) bool { return s*s >= tiles })
Checking two billion sizes one by one would take ages; binary search needs about 31 checks.
Task
This lesson's input is a list of seconds at which a doorbell rang.
- Complete
firstAtLeast(sorted []int, target int) int: the index of the first value>= target, orlen(sorted)when there is none. - Complete
countBetween(sorted []int, lo, hi int) int: how many values are betweenloandhi, both included. Whenhi < lo, that's0. - Complete
smallestSide(tiles int) int: the smallest whole numberswiths*s >= tiles. The tests go up totiles= 10^18, so search for the answer.