Java Equivalent of C++’s lower_bound() Method
The lower_bound() method of C++ return the index of the first element in the array which has a value not less than key. This means that the function returns the index of the next smallest number just greater than or equal to that number. If there are multiple values that are equal to the number, lower_bound() returns the index of the first such value.
Input : 4 6 10 12 18 18 20 20 30 45 Output : lower_bound for element 18 at index 4
Input : 4 6 10 12 16 20 28 Output : lower_bound for element 18 at index 5
Input : 24 26 40 56 Output : lower_bound for element 18 at index 0
Input : 4 6 10 12 16 17 Output : lower_bound for element 18 at index 6
Now let us discuss out the methods in order to use lower bound() method in order to get the index of the next smallest number just greater than or equal to that number.
- Naive Approach
- Using binary search iteratively
- Using binary search recursively
- Using binarySearch() method of Arrays utility class
Method 1: Using linear search
We can use linear search to find lower bound. We will iterate over the array starting from the 0th index until we find a value equal to or greater than the key.
Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(1)
We can use an efficient approach of binary search to search the key in the sorted array in O(log2 n) as proposed in the below example
Method 2: Using binary search iteratively
- Initialize the low as 0 and high as N.
- Compare key with the middle element(arr[mid])
- If the middle element is greater than or equals to key then update the high as a middle index(mid).
- Else update low as mid + 1.
- Repeat step 2 to step 4 until low is less than high.
- After all the above steps the low is the lower_bound of a key in the given array.
Now as usual optimizing further away by providing a recursive approach following the same procedure as discussed above.
Method 3: Using binary search recursively
We can also use the in-built binary search implementation of Arrays utility class (or Collections utility class). The function returns an index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array.
- Search the index of the key in a sorted array, returns index of the key as positive value of it is present in the array, otherwise, a negative value which specifies.
- The position at which the key should be added in the sorted array.
- Now if the key is present in the array we move leftwards to find its first occurrence else decrement the index to find the first occurrence of the key.
- Sort the array before applying binary search
- Print it
Note: We can also find mid-value via any one of themint mid = (high + low)/ 2;int mid = (low + high) >>> 1;