Java BinarySearch

前端 未结 10 2159
忘了有多久
忘了有多久 2020-12-09 23:33

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and

10条回答
  •  旧时难觅i
    2020-12-09 23:33

    /**
    HOPE YOU LIKE IT
    A.K.A Binary Search
    Take number array of 10 elements, input a number a check whether the number 
    is present:
    **/
    package array;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    class BinaryS
    {
        public static void main(String args[]) throws IOException
        {       
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));      
        System.out.print("Enter a number: ");
        int n=Integer.parseInt(br.readLine());
        int a[]={10,20,30,40,50,60,70,80,90,100};
        int upper=a.length-1,lower=0,mid;
        boolean found=false;
        int pos=0;
        while(lower<=upper)
        {
            mid=(upper+lower)/2;
            if(na[mid])lower=mid+1;
            else
            {
                found=true;
                pos=mid;
                break;
            }
        }
        if(found)System.out.println(n+" found at index "+pos);
        else System.out.println(n+" not found in array");
    }
    }
    

提交回复
热议问题