In this post, we will see how to perform binary search in java using divide and conquer method.When you want to find a value in sorted array,
we use binary search and we will also see how to compute time complexity of binary search.
Algorithm:
-
Initialize
first=0
andlast=sortedArray.length-1
-
compute mid and compare
sortedArray[mid]
with element to be searched -
If element to be searched is less than
sortedArray[mid]
then element lies in left part of the mid, solast=mid-1
-
if element to be searched is greater than
sortedArray[mid]
then element lies in right part of the mid, sofirst=mid+1
. -
if element to be searched is equal to
sortedArray[mid]
, then return index - Repeat above process until first is less than last.
-
public static int binarySearch(int[] sortedArray, int elementToBeSearched) { int first = 0; int last = sortedArray.length - 1; while (first <= last) { int mid = (first + last) / 2; // Compute mid point. if (elementToBeSearched < sortedArray[mid]) { last = mid-1; // repeat search in first half. } else if (elementToBeSearched > sortedArray[mid]) { first = mid + 1; // Repeat sortedArray in last half. } else { return mid; // Found it. return position } } return -1; // Failed to find element }
Now lets assume our sorted array is:
int[] sortedArray={12,56,74,96,112,114,123,567};
and we want to search for 74 in above array. Below diagram will explain
how binary search will work here.
When you observe closely, in each of the iteration you are cutting scope
of array to the half. In every iteration, we are overriding value of first
or last depending on sortedArray[mid]
.
Generalizing above equation:
For ith iteration : n/2
So iteration will end , when we have 1 element left i.e. for any i, which will be our last iteration:
so it concludes that number of iteration requires to do binary search is log(n) so complexity of binary search is log(n)
It makes sense as in our example, we have n as 8 . It took 3
iterations(8->4->2->1) and 3 is log(8).
Code:
public class BinarySerarchMain { public static int binarySearch(int[] sortedArray, int elementToBeSearched) { int first = 0; int last = sortedArray.length - 1; while (first <= last) { int mid = (first + last) / 2; // Compute mid point. if (elementToBeSearched < sortedArray[mid]) { last = mid-1; // repeat search in first half. } else if (elementToBeSearched > sortedArray[mid]) { first = mid + 1; // Repeat sortedArray in last half. } else { return mid; // Found it. return position } } return -1; // Failed to find element } public static void main(String[] args) { int[] sortedArray={12,56,74,96,112,114,123,567}; int indexOfElementToBeSearched=binarySearch(sortedArray,74); System.out.println("Index of 74 in array is: " +indexOfElementToBeSearched); int indexOfElementToBeSearchedNotFound=binarySearch(sortedArray,7); System.out.println("Index of 7 in array is: " +indexOfElementToBeSearchedNotFound); } }
when you run above program, you will get below output: