My first Codeforces blog post! Hooray!
This post was inspired by the problem: E. Iva & Pav of Codeforces round 900 (https://codeforces.me/contest/1878/problem/E).
Introduction
Most of you already know about binary search, what to use it for and its basic algorithm. This is not what I want to show here as it has already been done by more qualified people. I want to list all the slightly different binary search algorithms so that we can understand where to apply each of them.
The Problem
For this problem I tried applying basic binary search, lower bound and upper bound but didn't succeed. Here we are required to find the last element which satisfies the given condition thus requiring a slightly different binary search algorithm. Unfortunately I was not able to find a comprehensive list of binary search algorithms. So After years (about 0.01 years) of painstaking research I finally found five algorithms that will satisfy most problems regarding binary search.
The Algorithms
The Basic Binary search algorithm only applies for arrays with distinct elements. If the array has multiple instances of one element we need to apply a different algorithm. For example you could need any of the following elements for your specific problem.
Ex- [1, 2, 3, 5, 6, 8, 9, 10] key = 5 Ex- [1, 1, 1, 2, 2, 3, 4, 4, 4, 7, 7, 9] key = 4
These are the five algorithms for ascending order respectively in the order of the index of required element in array:
Their corresponding decreasing array counterparts:
Important Takeaways
The main point we can gleam from these algorithms is that when you get an element that satisfies the given condition, you immediately set result = mid. Although quite obvious some algorithms I read don't set a different variable for result and only take the value of mid after the loop ends as the answer which can be fail sometimes. Another important point to note is that the pointer we move (l or r) depends on whether we want the first element or the last element, not whether the array is ascending or descending. If we want the first element we set r = mid-1 and for last element we set l = mid+1 when we get required condition.
Hopefully this Blog can help someone ^~^!
Note
My problem requires use of 4th algorithm from descending set.



