Binary search is one of the searching techniques applied when the input is sorted here we are focusing on finding the middle element that acts as a reference frame whether to go left or right to it as the elements are already sorted. This searching helps in optimizing the search technique with every iteration is referred to as binary search and readers do stress over it as it is indirectly applied in solving questions.
Binary Search Algorithm in Java
Below is the Algorithm designed for Binary Search:
- Start
- Take input array and Target
- Initialise start = 0 and end = (array size -1)
- Intialise mid variable
- mid = (start+end)/2
- if array[ mid ] == target then return mid
- if array[ mid ] < target then start = mid+1
- if array[ mid ] > target then end = mid-1
- if start<=end then goto step 5
- return -1 as Not element found
- Exit
Now you must be thinking what if the input is not sorted then the results are undefined.
Note: If there are duplicates, there is no guarantee which one will be found.
Methods for Java Binary Search
There are three methods in Java to implement Binary Search in Java are mentioned below:
- Iterative Method
- Recursive Method
- Inbuild Method
1. Iterative Method for Binary Search  in Java
Below is the implementation is mentioned below:
Java
class BinarySearch {
int binarySearch( int arr[], int l, int r, int x)
{
while (l <= r) {
int mid = (l + r) / 2 ;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
r = mid - 1 ;
} else {
l = mid + 1 ;
}
}
return - 1 ;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2 , 3 , 4 , 10 , 40 };
int n = arr.length;
int x = 10 ;
int result = ob.binarySearch(arr, 0 , n - 1 , x);
if (result == - 1 )
System.out.println( "Element not present" );
else
System.out.println( "Element found at index "
+ result);
}
}
|
Output
Element found at index 3
Tip: Geeks you must be wondering out whether there is any function like lower_bound() or upper_bound() just likely found in C++ STL. so the straight answer is that there was no function only till Java 9, later onwards they were added.Â
2. Recursive Method for Binary Search
Below is the implementation of the above method:
Java
class BinarySearch {
int binarySearch( int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2 ;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1 , x);
return binarySearch(arr, mid + 1 , r, x);
}
return - 1 ;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2 , 3 , 4 , 10 , 40 };
int n = arr.length;
int x = 10 ;
int result = ob.binarySearch(arr, 0 , n - 1 , x);
if (result == - 1 )
System.out.println(
"Element is not present in array" );
else
System.out.println(
"Element is present at index " + result);
}
}
|
Output
Element is present at index 3
Complexity of the above method
Time Complexity: O(log N)
Space Complexity: O(1), If the recursive call stack is considered then the auxiliary space will be O(log N)
3. In Build Method for Binary Search in Java
Arrays.binarysearch()Â works for arrays which can be of primitive data type also.
Below is the implementation of the above method:
Java
import java.util.Arrays;
public class GFG {
public static void main(String[] args)
{
int arr[] = { 10 , 20 , 15 , 22 , 35 };
Arrays.sort(arr);
int key = 22 ;
int res = Arrays.binarySearch(arr, key);
if (res >= 0 )
System.out.println(
key + " found at index = " + res);
else
System.out.println(key + " Not found" );
key = 40 ;
res = Arrays.binarySearch(arr, key);
if (res >= 0 )
System.out.println(
key + " found at index = " + res);
else
System.out.println(key + " Not found" );
}
}
|
Output
22 found at index = 3
40 Not found
Binary Search in Java Collections
Now let us see how Collections.binarySearch() work for LinkedList. So basically as discussed above this method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
Collections.binarysearch()Â works for objects Collections like ArrayList and LinkedList.Â
Below is the implementation of the above method:Â
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add( 1 );
al.add( 2 );
al.add( 3 );
al.add( 10 );
al.add( 20 );
int key = 10 ;
int res = Collections.binarySearch(al, key);
if (res >= 0 )
System.out.println(
key + " found at index = " + res);
else
System.out.println(key + " Not found" );
key = 15 ;
res = Collections.binarySearch(al, key);
if (res >= 0 )
System.out.println(
key + " found at index = " + res);
else
System.out.println(key + " Not found" );
}
}
|
Output
10 found at index = 3
15 Not found
The complexity of the above method
Time complexity: O(log N)
Auxiliary space: O(1)
Last Updated :
05 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...