Thursday, 11 August 2016

Binary Search java program

import java.io.*;
class binary
{
    public static void main(String []args) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int a[]=new int[10];
        int i,key,flag=0,n;
        int top,bott;
        System.out.println("Enter the no of elements");
        n=Integer.parseInt(br.readLine());
        System.out.println("Enter the Values in sorted order");
        for(i=0;i<n;i++)
        a[i]=Integer.parseInt(br.readLine());       
        System.out.println("Enter the Search element");
        key=Integer.parseInt(br.readLine());
        top=0;bott=n-1;
        int mid=(top+bott)/2;
        while(top <= bott && flag == 0)
           {
               mid = (top + bott) /2 ;
               if(a[mid] == key)
          flag = 1;
        else if(a[mid]>key)
           top = mid + 1;
        else
           bott = mid - 1;
        }

        if(flag==1)
        System.out.println("Search Element found at location "+(mid+1));
        else
        System.out.println("Search Element Not found");
    }
}

No comments: