B Search
B Search
BINARY SEARCH
CODECLASS[49]
▸ Arr[i] = F(i)
▸ So Arr = [……,-4,1,6,11,………]
is equivalent to
F(0) = 1
F(1) = 3
F(2) = 55
F(3) = 92
F(4) = 189
MONOTONIC FUNCTION
▸ A monotonic function is a function between ordered sets that
preserves or reverses the given order.
A PROBLEM
▸ FairWorkload Problem - Given an array of workloads, split it among ‘k’
workers, such that the maximum work that any worker has to do is
minimised (can’t change order of workloads). Print as answer that
maximum work.
▸ Eg. 10 20 30 40 50 60 70 80 90
Solution : 10 20 30 40 50 | 60 70 | 80 90
First worker - 150,
Second worker - 130,
Third worker - 170
A SIMPLER PROBLEM
▸ FairWorkLoad simplified- Given an array of workloads, split it among ‘k’
workers, such that the maximum work that any worker has to do is less
than K. If split is possible, print answer as true, else print false.
▸ Eg. 10 20 30 40 50 60 70 80 90,
K = 170
Solution : 10 20 30 40 50 | 60 70 | 80 90
First worker - 150,
Second worker - 130,
Third worker - 170
SOLVE ORIGINAL PROBLEM USING
SOLUTION TO SIMPLER PROBLEM
+
BINARY SEARCH
CODECLASS[49]
▸ Binary search can be used if and only if for all x in S, p(x) implies p(y) for all y > x.
This property is what we use when we discard the second half of the search
space.
▸ It is equivalent to saying that ¬p(x) implies ¬p(y) for all y < x (the symbol ¬
denotes the logical not operator), which is what we use when we discard the
first half of the search space.
▸ Behind the cryptic mathematics I am really stating that if you had a yes or no
question (the predicate), getting a yes answer for some potential solution x means
that you’d also get a yes answer for any element after x. Similarly, if you got a no
answer, you’d get a no answer for any element before x. As a consequence, if you
were to ask the question for each element in the search space (in order), you
would get a series of no answers followed by a series of yes answers.
▸ Careful readers may note that binary search can also be used when a predicate
yields a series of yes answers followed by a series of no answers. This is true and
complementing that predicate will satisfy the original condition. For simplicity we’ll
deal only with predicates described in the theorem.
▸ We can use binary search to find the smallest legal solution, i.e. the smallest x
for which p(x) is true.
CODECLASS[49]
Predicate example
DISCUSSION,
SUMMARY AND
PRACTICE QUESTIONS