Java Equivalent of C++’s upper_bound() Method

• Last Updated : 14 Jan, 2022

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:

1. Naive Approach (linear search)
2. Iterative binary search
3. Recursive binary search
4. binarySearch() method of Arrays utility class

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

Java

 // Java program for finding upper bound // using linear search   // Importing Arrays utility class import java.util.Arrays;   // Main class class GFG {       // Method 1     // To find upper bound of given key     static void upper_bound(int arr[], int key)     {         int upperBound = 0;           while (upperBound < arr.length) {             // If current value is lesser than or equal to             // key             if (arr[upperBound] <= key)                 upperBound++;               // This value is just greater than key             else{                 System.out.print("The upper bound of " + key + " is " + arr[upperBound] + " at index " + upperBound);                   return;             }            }         System.out.print("The upper bound of " + key + " does not exist.");     }       // Method 2     // Main driver method     public static void main(String[] args)     {         // Custom array input over which upper bound is to         // be operated by passing a key         int array[] = { 10, 20, 30, 30, 40, 50 };         int key = 30;           // Sort the array using Arrays.sort() method         Arrays.sort(array);           // Printing the upper bound         upper_bound(array, key);     } }

Output

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:

1. Sort the array before applying binary search.
2. Initialize low as 0 and high as N.
3. Find the index of the middle element (mid)
4. Compare key with the middle element(arr[mid])
5. If the middle element is less than or equals to key then update the low as mid+1, Else update high as mid.
6. Repeat step 2 to step 4 until low is less than high.
7. After all the above steps the low is the upper_bound of the key

Example

Java

 // Java program to Find upper bound // Using Binary Search Iteratively   // Importing Arrays utility class import java.util.Arrays;   // Main class public class GFG {       // Iterative approach to find upper bound     // using binary search technique     static void upper_bound(int arr[], int key)     {         int mid, N = arr.length;           // Initialise starting index and         // ending index         int low = 0;         int high = N;           // Till low is less than high         while (low < high && low != N) {             // Find the index of the middle element             mid = low + (high - low) / 2;               // If key is greater than or equal             // to arr[mid], then find in             // right subarray             if (key >= arr[mid]) {                 low = mid + 1;             }               // If key is less than arr[mid]             // then find in left subarray             else {                 high = mid;             }         }           // If key is greater than last element which is         // array[n-1] then upper bound         // does not exists in the array         if (low == N ) {             System.out.print("The upper bound of " + key + " does not exist.");              return;              }             // Print the upper_bound index           System.out.print("The upper bound of " + key + " is " + arr[low] + " at index " + low);     }       // Driver main method     public static void main(String[] args)     {         int array[] = { 10, 20, 30, 30, 40, 50 };         int key = 30;           // Sort the array using Arrays.sort() method         Arrays.sort(array);           // Printing the upper bound         upper_bound(array, key);     } }

Output

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

Java

 // Java program to Find Upper Bound // Using Binary Search Recursively   // Importing Arrays utility class import java.util.Arrays;   // Main class public class GFG {       // Recursive approach to find upper bound     // using binary search technique     static int recursive_upper_bound(int arr[], int low,                                      int high, int key)     {         // Base Case         if (low > high || low == arr.length)             return low;           // Find the value of middle index         int mid = low + (high - low) / 2;           // If key is greater than or equal         // to array[mid], then find in         // right subarray         if (key >= arr[mid]) {             return recursive_upper_bound(arr, mid + 1, high,                                          key);         }           // If key is less than array[mid],         // then find in left subarray         return recursive_upper_bound(arr, low, mid - 1,                                      key);     }       // Method to find upper bound     static void upper_bound(int arr[], int key)     {         // Initialize starting index and         // ending index         int low = 0;         int high = arr.length;           // Call recursive upper bound method         int upperBound             = recursive_upper_bound(arr, low, high, key);         if (upperBound == arr.length)             // upper bound of the key does not exists             System.out.print("The upper bound of " + key                              + " does not exist.");         else System.out.print(                 "The upper bound of " + key + " is "                 + arr[upperBound] + " at index "                 + upperBound);     }       // Main driver method     public static void main(String[] args)     {           int array[] = { 10, 20, 30, 30, 40, 50 };         int key = 30;           // Sorting the array using Arrays.sort() method         Arrays.sort(array);           // Printing the upper bound         upper_bound(array, key);     } }

Output

The upper bound of 30 is 40 at index 4

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:

1. Sort the array before applying binary search.
2. Search the index of the key in a sorted array, if it is present in the array, its index is returned as positive value of , otherwise, a negative value which specifies the position at which the key should be added in the sorted array.
3. Now if the key is present in the array we move rightwards to find next greater value.
4. Print the upper bound index if present.

Example

Java

 // Java program to find upper bound // Using binarySearch() method of Arrays class   // Importing Arrays utility class import java.util.Arrays;   // Main class public class GFG {       // Method 1     // To find upper bound using binary search     // implementation of Arrays utility class     static void upper_bound(int arr[], int key)     {         int index = Arrays.binarySearch(arr, key);         int n = arr.length;           // If key is not present in the array         if (index < 0) {               // Index specify the position of the key             // when inserted in the sorted array             // so the element currently present at             // this position will be the upper bound             int upperBound = Math.abs(index) - 1;             if (upperBound < n)                 System.out.print("The upper bound of " + key                                  + " is " + arr[upperBound]                                  + " at index "                                  + upperBound);             else                 System.out.print("The upper bound of " + key                                  + " does not exists.");             return;         }           // If key is present in the array         // we move rightwards to find next greater value         else {               // Increment the index until value is equal to             // key               while (index < n) {                   // If current value is same                 if (arr[index] == key)                     index++;                   // Current value is different which means                 // it is the greater than the key                 else {                     System.out.print(                         "The upper bound of " + key + " is "                         + arr[index] + " at index "                         + index);                     return;                 }             }             System.out.print("The upper bound of " + key                              + " does not exist.");         }     }       // Method 2     // Main driver method     public static void main(String[] args)     {         int array[] = { 10, 20, 30, 30, 40, 50 };         int key = 30;           // Sort the array before applying binary search         Arrays.sort(array);           // Printing the lower bound         upper_bound(array, key);     } }

Output

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;

My Personal Notes arrow_drop_up
Recommended Articles
Page :