awelgorithms

Binary search needs a monotonic predicate

Updated

Binary search can drop half the indices only when a test is true on a prefix of the array and false on the suffix (or the reverse). That single cut is the monotonic predicate.

What to focus on

List pred(i) = a[i] < t for every index. One cut (TTTFFF) licenses the search. Two or more cuts mean the array is not sorted for this test and a mid drop could discard the answer.

Worked examples

one cut

a = [1, 4, 9], t = 5
  1. 1 < 5, 4 < 5, 9 < 5

Result: [true, true, false]

two cuts

a = [4, 1, 9], t = 2
  1. 4 < 2, 1 < 2, 9 < 2
  2. not monotonic

Result: [false, true, false]

empty

a = [], t = 4
  1. no index to test

Result: []

Try it

Write predList(a, t). a is an array of integers and may be empty. t is the target. Return the list of a[i] < t for every index in order. A list with one change from true to false is monotonic and safe to binary search. On [1, 4, 9] with t = 5 return [true, true, false]. On [4, 1, 9] with t = 2 return [false, true, false]. On [] return [].

a is an integer array and may be empty. t is an integer.