Binary Search Framework

Use Binary Search to find the first/last element with a property in a sorted array.

l: first position in your consideration
h: last position in your consideration, even can larger than the last index of the array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
while (l < h) {
// first element
m_l = l + (h - l) / 2
if (!Satisfy(m_l)) {
l = m + 1
} else {
h = m
}
/*
// last element
m_h = l + (h - l) / 2 + 1
if (!Satisfy(m_h)) {
h = m - 1
} else {
l = m
}
*/
}

The idea is that if the mid point satisfies a property, then keep the opposite bound of round at mid, otherwise move the corresponding bound toward mid exceed 1.
Finally its true that l == h

Show comments from Gitment