Title

JAVA

      In this blog, you will find programs on JAVA and also some help on how to write programs for JAVA...

December 18, 2014

Binary Search


import java.util.Scanner;

public class BSearch
{
    public static void main()
    {
        Scanner s=new Scanner(System.in);
        System.out.print("Enter the no you want to find: ");
        int n=s.nextInt();
        int m[]={12,45,34,23,1,3,2,7,98}, lo=0, hi=m.length-1, mid=(hi + lo)/2;
        boolean found=false;
        while(lo<=hi)
        {
            if(m[mid]==n)
            {
                found=true;
                break;
            }
            if(n>m[mid])
                lo=mid+1;
                else
                hi=mid-1;
            mid=(hi+lo)/2;
        }
        if(found==true)
            System.out.println("Found");
            else
            System.out.println("Not Found");
    }
}

No comments:

Post a Comment

Please write your comment in the box below...