Solution: Find the Floor and Ceil of a Number
Explore how to apply a modified binary search algorithm to determine the floor and ceil of a target number in a sorted array. This lesson guides you through step-by-step code explanations that illustrate how to update search boundaries and maintain efficient searching to achieve a time complexity of O(log n).
We'll cover the following...
Solution
We can make use of the fact that the array is sorted. So, by a little modification of the binary search algorithm, we can successfully crack this problem. The core idea remains the same: we divide the array at the midpoint and search for the key either in left or right subarray based on the comparison with a given number.
Here is the complete working solution:
Explanation
Let’s take you to the step-by-step code break down to gain a better understanding of the solution:
- Line 44 - 48: The wrapper function explicitly calls
findFloor(input, x)andfindCeiling(input, x), respectively, and stores the result in the array called output.
...