Binary Search, is one of the first algorithms taught to computer science students. It is a simple, divide and conquer algorithm, which can be implemented iteratively or recursively without much trouble. The simplicity and efficacy of binary search serves as a prime example of how a carefully chosen algorithm can make a big impact on the performance of the application. The following points define binary search accurately:
Binary Search:Below is the implementation of binary search in Python.
Monotonic functions are functions that are constantly increasing or constantly decreasing throughout the domain of the function. Often in algorithms, we are required to find a optimal point in this monotonic function (which has a huge domain, ruling out brute force). In such cases, binary search comes to our rescue.
The idea of finding the optimal point in the domain of a monotone is similar to the traditional binary search, only this time, instead of an array, we have the following:
# f is monotone
ans = inf # -inf if searching for maximal value
lo = domain_low, hi = domain_high
while lo <= hi:
mid = (lo + hi)/2
val = f(mid)
check val with threshold:
if admissible:
update ans if val is better
discard the half of domain space that is useless
else:
discard the other half
Link to the problem: SPOJ Aggressive Cows
It is recommended that before reading the content below, keeping the idea that we discussed above, give the problem a go.
Binary search can often be used for problems that involve finding the optimal point, on a monotonic function. The running complexity of O(log n), without any additional space requirement, and its nature of being simple to implement makes binary search a frequently used algorithm in such situations.
Well then, until next time!