Sunday, April 18, 2010

Binary search

import java.io.*;
class Binary
{
    int search(int[] a,int r,int l,int x)

    {
        if(l>r)
            return -1;
        int mid=(r+l)/2;
       
        if (x==a[mid])
            return mid;
        else if (x>a[mid])
            return search(a,mid-1,l,x);
        else if (x
             return search(a,r,mid+1,x);
            else return -1;
          
    }
}
class Test
{
    public static void main(String[] args)throws Exception
    {
        Binary b=new Binary();
        BufferedReader d=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the size of the array");
        int n=Integer.parseInt(d.readLine());
        int[] a=new int[n];
        System.out.println("Enter the array");
        for(int i=0;i<=a.length-1;i++)
        {
        a[i]=Integer.parseInt(d.readLine());
        }
        System.out.println("Enter the no. to find");
        int x=Integer.parseInt(d.readLine());
        int l,r,mid;
        l=0;
        r=a.length-1;
                int pos=b.search(a,r,l,x);
        if (pos==-1)
        {
            System.out.println("No. not found");
        }
        else
        {
            System.out.println("no. found at"+(pos+1));
        }
    }
}

/*Output
Enter the size of the array
5
Enter the array
10 20 30 40 50
Enter the no. to find 30
no. found at3

Process Exit...
*/       
       

0 comments:

Post a Comment

 
ShareThis

Visitor

Website counter
Copyright 2009 Code's. Powered by Blogger
Blogger Templates created by Deluxe Templates
Wordpress by Wpthemescreator
Blogger Showcase