The binary search algorithm is used to search an element in the sorted array. It’s faster than linear search and improves perfomance from O(n) to O(logN) for searching an element in the array. In order to perform the binary search, you need a sorted array, so you can either ask the user to enter array in sorted order or you should sort the array before perfoming the binary search. In this article, we will write a Java program which will take input form the user, both array and the number to be serached and then perform a binary search to find that number in given arry. We will not use the Collenctions.binarySearch()method instead we will write our own methodperformBinarySearch(int[] inputArray, int targetNum).
In order to implement binary search, you must first know how how binary search works? if you don not know the algorithm you cannot code it. So, let us first revise the binary search algorithm itself.
How Binary Search Algorithm works
if you remember something about searching algorithms form you data structure and algorithm calsses in college you might know that binary search works on the principle of divede and conquer. In this techique, a solution is found by dividing the inputArray on some rules.
In binary search algorithm, you first find the middle element of the array and compare that with the number you are searching. If it is equal then you return true or index of that number and you binary search is complete but if it does not match then you divide the array in two parts based upon whether the middle element is greater that or less than the key value, which you are searching.
if the key is greater than middle element than search value in the second half of array because the array is sorted in increasing order. Similarily, if the key is lower than middle element it means it is in the first part of the array.
How to implement Binary Search in Java without Recursion
Here is my implementation of the popular binary search algorithm in Java. Though, you don not need to implement this algorithm if you want to use it in your production code. JDK collection API already has a binarySearch() method on the Arrays class.
import java.util.Scanner;
publicclass BinarySearch{
publicstaticvoidmain(String[] args){
Scanner commandReader = new Scanner(System.in);
System.out.println("Enter total number of elements : ");
int length = commandReader.nextInt();
System.out.printf("Enter %d integers %n", length);
for(int i = 0 ; i < length; i++){
inputArray[i] = commandReader.nexInt();
}
System.out.println("Please enter number to be searched in array (sorted order)");
int key = commandReader.nexInt();
int index = performBinarySearch(inputArray, key);
if(index = -1) System.out.printf("Sorry, %d is not found in array %n", key);
else System.out.printf("%d is found in array at index %d %n", key, index);
commandReader.close();
}
publicstaticintperformBinarySearch(int[] inputArray, int target){
int low = 0;
int high = inputArray.length - 1;
while(low <= high){
int middle = (low + high) / 2;
if(target == middle) return middle;
elseif (target < middle) high = middle - 1;
else low = middle + 1;
}
return -1;
}
}
This is an iterative solution of the binary search problem. The time complexity of binary search is in order of O(logN) if you get the sorted input. If you have to sort the input then you need to add that time on the total run time of the algorithm as well.
How to implement binary search suing recursion.
In order to implement a recursive solution, you need a base case because without a base case your program will never terminate and it will eventually die by throwing StackOverFlowError. In the case of recursive binary search implementation, we calculate middle position by taking start and end position and check if the target element is equal to the middle element or not.
So, in each iteration, the value of start and end position changes. At first, start = 0 and end = length - 1 but then depending the value of target element we move the pointer to first or second half of array. This gives you the base case. since the array is getting smaller and smaller in every iteration at one point it will limit to just one element and after that end will be less than the start. At this point, you can stop the binary search because now you can not divide the array further, which means element does not exist in the array. Our solution return -1 at this point of time.
Here is our complete Java solution to implement a recursive binary search. I have a public method recursiveBinarySearch(int[] inputArray, int start, int end, int target) Now the recursive logic is very simple, we calculate middle index by using start and end paratmeter passed to this method, which 0 and length - 1 at the start. After that, we retrieve middle element and compare it with the key or target. If it is equal then we return the index otherwise, we repeat the binary search in the first half or second half of array depending upon whether the key is smaller than the middle element or larger than the key.
/**
method which implement recursive binary search algorithm
* @param inputArray*
* @param start
* @param end
* @param target
* @return index of target element or -1 if not found */publicstaticintrecursiveBinarySearch(int[] inputArray, int start, int end, int target){
if(start > end) return -1;
int middle = (start + end) / 2;
if(target == inputArray[middle]) return middle;
elseif(target < imputArray[middle]) return recursiveBinarySearch(inputArray, start, middle - 1, target);
elsereturn recursiveBinarySearch(inputArray, middle + 1, end, target);
}