Friday, April 15, 2011

Binary Search – Simple


import java.util.Scanner;
class BinarySearch
{
    static int Binary_Search(int K[ ],int n,int KEY)
    {
        int low=1,high=n,mid;
        mid=(low+high)/2;
        while (high>=low)
        {
            if (K[mid]==KEY)
                return(mid);
            else
            {
                if(KEY>K[mid])
                    low=mid+1;
                else
                    high=mid-1;
                mid=(low+high)/2;
            }
        }
        return(-1);
    }
    public static void main(String args[ ])
    {
        int i,KEY,flag=0;
        int x[] = new int[25];

        Scanner in = new Scanner(System.in);
        System.out.println("Enter 10 number in ascending order");
        for(i=1;i<10;i++)
            x[i] = in.nextInt();
        System.out.print("Enter the number to be searched  : ");
        KEY = in.nextInt();
        flag = Binary_Search(x,10,KEY);
        if (flag == -1)
            System.out.println(" Number Not present in the given array");
        else
            System.out.println(" Number "+KEY+" found at "+flag+" location in the array");
    }
}

No comments:

Post a Comment