Saturday, 13 February 2016

Binary search program using array

Non-Recursive :
import java.util.Scanner;

public class BinarySearch {

    public static int search(int[] a, int searchKey) {
          int start = 0, end = a.length-1;

          while(start <= end) {
              int mid = (start + end)/2;

              if(searchKey == a[mid])
                   return mid;
              if(searchKey < a[mid])
                   end = mid-1;
              else
                   start = mid+1;
          }
          return -1;
    }

    public static void main(String[] args) {
          Scanner input = new Scanner(System.in);

          System.out.print("\n Enter the length of array : ");
          int size = input.nextInt();

          int[] ar = new int[size];
          System.out.println("\n Enter " + size + " integer (sorted order) : ");

          for(int i=0; i<size; i++)
              ar[i] = input.nextInt();

          System.out.print(" Enter Search Item : ");
          int searchKey = input.nextInt();

          int temp = search(ar, searchKey);

          if(temp == -1)
              System.out.println("\n Item not found ");
          else
              System.out.println("\n Item found at position : " + (temp+1));
    }//End of main()
}//End of BinarySearch class

Output:



Recursive :
import java.util.Scanner;

public class BinarySearchRecursive {

    static int search(int[] a, int low, int high, int searchKey) {

        if(low>high)
            return -1;

        int mid = (low + high)/2;

        if(searchKey == a[mid])
            return mid;

        if(searchKey < a[mid])
            return search(a, low, mid-1, searchKey);
        else
            return search(a, mid+1, low, searchKey);
    }

    public static void main(String[] args) {
          Scanner input = new Scanner(System.in);

          System.out.print("\n Enter the length of array : ");
          int size = input.nextInt();
          int[] ar = new int[size];

          System.out.println("\n Enter " + size + " integer (sorted order) : ");

          for(int i=0; i<size; i++)
              ar[i] = input.nextInt();

          System.out.print(" Enter Search Item : ");
          int searchKey = input.nextInt();
         
          int temp = search(ar, 0, ar.length, searchKey);

          if(temp == -1)
              System.out.println("\n Item not found ");
          else
              System.out.println("\n Item found at position : " + (temp+1));
    }//End of main()
}//End of BinarySearchRecursive class

Output:



No comments:

Post a Comment