How to do binary search in java.

As earlier we have read out about  linear search in java,here we are going to read about binary search.Binary search make searching more easier as compared to linear search.Binary search divides the whole array in two equal parts after dividing it compares the value at mid to value whose position we want to check if it find the same value than it will print it’s position otherwise it will check that the value is from the left or from the right part of the array,if the value is from right part than the searching start from mid+1 to last element , otherwise value will be at left to the  mid than the searching start from 0 to mid-1.This process continues till the value is found at mid or if left value is more than right then the value is not present in array.

   Java code for binary search is:-

      import java.util.Scanner; 

      public class binarysearch2 {

          public static void main(String[] args) {
         Scanner s = new Scanner(System.in);
         int a[] = {-6, -2, 1, 3, 5, 7, 8, 22, 30};
        int n, l = 0, r = a.length – 1;
      System.out.println(“Enter the number whose position you want to check=”);
      n = s.nextInt();
      while (true) {
      int mid = (l + r) / 2;
     if (a[mid] == n) {
      System.out.println(“Value found at position ” + mid);
        break;
          }
         if (n < a[mid]) {
          r  = mid – 1;
             } else {
             l = mid + 1;
                }

           if (l > r) {
           System.out.println(“Value not found”);
          break;
            }

              } 
          }

      }

The output is:-

Leave a Reply