![]() |
VOOZH | about |
In this article, we will discuss Java's equivalent implementation of the upper_bound() method of C++. This method is provided with a key-value which is searched in the array. It returns the index of the first element in the array which has a value greater than key or last if no such element is found. The below implementations will find the upper bound value and its index, otherwise, it will print upper bound does not exist.
Illustrations:
Input : 10 20 30 30 40 50 Output : upper_bound for element 30 is 40 at index 4
Input : 10 20 30 40 50 Output : upper_bound for element 45 is 50 at index 4
Input : 10 20 30 40 50 Output : upper_bound for element 60 does not exists
Now let us discuss out the methods in order to use the upper bound() method in order to get the index of the next greater value.
Methods:
Let us discuss each of the above methods to detailed understanding by providing clean java programs for them as follows:
Method 1: Using linear search
To find the upper bound using linear search, we will iterate over the array starting from the 0th index until we find a value greater than the key.
Example
The upper bound of 30 is 40 at index 4
Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(1)
To find the upper bound of a key, we will search the key in the array. 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 examples.
Method 2: Using binary search iteratively
Procedure:
Example
The upper bound of 30 is 40 at index 4
A recursive approach following the same procedure is discussed below:
Method 3: Recursive binary search
Example
The upper bound of 30 is 40 at index 4
Method 4: Using binarySearch() method of Arrays utility class
We can also use the in-built binary search method of Arrays utility class (or Collections utility class). This function returns an index of the key in the array. If the key is present in the array it will return its index (not guaranteed to be the first index), otherwise based on sorted order, it will return the expected position of the key i.e (-(insertion point) – 1).
Approach:
Example
The upper bound of 30 is 40 at index 4
Note: We can also find the index of the middle element via any one of them
int mid = (high + low)/ 2;
int mid = (low + high) >>> 1;