Open darwinrlo opened 4 years ago
For binary search, use a while loop (as opposed to recursion). The loop condition can be start <= end. end is inclusive.
This pertains to the problem of finding the ceiling of a target element in an array that is sorted in non-decreasing order.
Assume that the target element is not in the array.
Say that the start index is pointing to the element just before the ceiling.
Say the end index has made it to the ceiling.
Say the middle element is at some point the ceiling.
If finding the floor instead of the ceiling, return the end index instead of the start index.
If the middle element is greater than the target element,
Example: [1, 2, 5, 7], target = 4
Example: [1, 2, 3, 5], target = 4
Example: [1, 3, 5, 7, 9], target = 4
Example: ..., 3, 5, ...; target = 4