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
// Java implementation of iterative Binary Search
class BinarySearch {
int binarySearch(int a[], int l, int r, int x)
{
while (l <= r) {
int m = (l + r) / 2;
// Index of Element Returned
if (a[m] == x) {
return m;
// If element is smaller than mid, then
// it can only be present in left subarray
// so we decrease our r pointer to mid - 1
} else if (a[m] > x) {
r = m - 1;
// Else the element can only be present
// in right subarray
// so we increase our l pointer to mid + 1
} else {
l = m + 1;
}
}
// No Element Found
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int a[] = { 2, 3, 4, 10, 40 };
int n = a.length;
int x = 10;
int res = ob.binarySearch(a, 0, n - 1, x);
if (res == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + res);
}
}
OutputElement 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
// Java implementation of
// recursive Binary Search
class BinarySearch {
int binarySearch(int a[], int l, int r, int x)
{
if (r >= l) {
int m = l + (r - l) / 2;
// Returned Index of the Element
if (a[m] == x)
return m;
// If element is smaller than mid, then
// it can only be present in left subarray
if (a[m] > x)
return binarySearch(a, l, m - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(a, m + 1, r, x);
}
// No Element Found
return -1;
}
// main function
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int a[] = { 2, 3, 4, 10, 40 };
int n = a.length;
int x = 10;
int res = ob.binarySearch(a, 0, n - 1, x);
if (res == -1)
System.out.println(
"Element is not present in array");
else
System.out.println("Element is present at index " + res);
}
}
OutputElement 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
// Java Program to demonstrate working of binarySearch()
// Method of Arrays class In a sorted array
import java.util.Arrays;
public class GFG {
public static void main(String[] args)
{
int a[] = { 10, 20, 15, 22, 35 };
// Sorting the above array
// using sort() method of Arrays class
Arrays.sort(a);
int x = 22;
int res = Arrays.binarySearch(a, x);
if (res >= 0)
System.out.println(x + " found at index = " + res);
else
System.out.println(x + " Not found");
x = 40;
res = Arrays.binarySearch(a, x);
if (res >= 0)
System.out.println(x + " found at index = " + res);
else
System.out.println(x + " Not found");
}
}
Output22 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
// Java Program to Demonstrate Working of binarySearch()
// method of Collections class
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> a = new ArrayList<Integer>();
// Populating the Arraylist
a.add(1);
a.add(2);
a.add(3);
a.add(10);
a.add(20);
int x = 10;
int res = Collections.binarySearch(a, x);
if (res >= 0)
System.out.println(x + " found at index = " + res);
else
System.out.println(x + " Not found");
x = 15;
res = Collections.binarySearch(a, x);
if (res >= 0)
System.out.println(x + " found at index = " + res);
else
System.out.println(x + " Not found");
}
}
Output10 found at index = 3
15 Not found
The complexity of the above method
Time complexity: O(log N)
Auxiliary space: O(1)