Java Equivalent of C++’s upper_bound() Method
Last Updated :
28 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:
- Naive Approach (linear search)
- Iterative binary search
- Recursive binary search
- 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);
}
}
OutputThe 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:
- Sort the array before applying binary search.
- Initialize low as 0 and high as N.
- Find the index of the middle element (mid)
- Compare key with the middle element(arr[mid])
- If the middle element is less than or equals to key then update the low as mid+1, Else update high as mid.
- Repeat step 2 to step 4 until low is less than high.
- 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);
}
}
OutputThe 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);
}
}
OutputThe 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:
- Sort the array before applying binary search.
- 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.
- Now if the key is present in the array we move rightwards to find next greater value.
- 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);
}
}
OutputThe 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;
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read