Given a sorted array arr[] of N integers and a number K, the task is to write the C program to find the upper_bound() and lower_bound() of K in the given array.
Examples:
Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 6
Output:
Lower bound of 6 is 6 at index 1
Upper bound of 6 is 10 at index 2
Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 20
Output:
Lower bound of 20 is 20 at index 5
Upper bound doesn't exist
Approach: The idea is to use Binary Search. Below are the steps:
- For lower_bound():
- Initialise the startIndex as 0 and endIndex as N - 1.
- Compare K with the middle element(say arr[mid]) of the array.
- If the middle element is greater equals to K then update the endIndex as a middle index(mid).
- Else Update startIndex as mid + 1.
- Repeat the above steps until startIndex is less than endIndex.
- After all the above steps the startIndex is the lower_bound of K in the given array.
- For upper_bound():
- Initialise the startIndex as 0 and endIndex as N - 1.
- Compare K with the middle element(say arr[mid]) of the array.
- If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1).
- Else Update endIndex as mid.
- Repeat the above steps until startIndex is less than endIndex.
- After all the above steps the startIndex is the upper_bound of K in the given array.
Below is the iterative and recursive implementation of the above approach:
Output: Lower bound of 6 is 6 at index 1
Upper bound of 6 is 10 at index 2
Time Complexity: O(log2 N), where N is the number of elements in the array.
Auxiliary Space: O(1).