Friday, April 15, 2011

Binary Search – Recursive


import java.util.Scanner;
public class BinSearchRecur
{
    static void BinSearch(int x[],int low,int high,int key)
    {
        int mid;
        if(low<=high)
        {
            mid=(low+high)/2;
            if(x[mid]==key)
                System.out.println("Element found at "+mid);
            if(x[mid]<key)
                BinSearch(x,mid+1,high,key);
            else
                BinSearch(x,low,mid-1,key);

        }
    }
    public static void main(String[] args)
    {
        Scanner in=new Scanner(System.in);
        int x[]=new int[10];
        int KEY,n=10;

        System.out.println("Enter 10 number in ascending order");
        for(int i=1;i<10;i++)
            x[i] = in.nextInt();
        System.out.print("Enter the number to be searched  : ");
        KEY = in.nextInt();
        BinSearch(x,0,n-1,KEY);
    }
}

No comments:

Post a Comment