Binary search in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
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 complexity of binary search.
Lets say we have an sorted array.

Algorithm:

  1. Initialize first=0 and last=sortedArray.length-1
  2. compute mid and compare  sortedArray[mid]  with element to be searched
  3. If element to be searched is less than sortedArray[mid] then element lies in left part of the mid, so last=mid
  4. if element to be searched is greater than sortedArray[mid] then element lies in right part of the mid, so first=mid+1.
  5. if element to be searched is equal to sortedArray[mid] , then return index
  6. 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;     // 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
  }

Example:
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].
So for
0th iteration : n
1th iteration: n/2
2nd iteration n/4
3rd iteration n/8.
Generalizing above equation:
For ith iteration : n/2i

So iteration will end , when we have 1 element left i.e. for any i, which will be our last iteration:
1=n/2i;
2i=n;
after taking log
i= log(n);
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:

 
package org.arpit.java2blog.thread;

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;     // 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:
  
Index of 74 in array is: 2
Index of 7 in array is: -1

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012