java--折半查找

package zheban;
import java.util.Scanner;

public class Zheban {
    public static void main(String[] args) {
        int start=0,end,mid;
        int a[]={12,45,65,98,56,-23,3};
        int N=a.length;
        for(int i=0;i<N;i++)        //选择法排序
        {
            for(int j=i+1;j<N;j++)
            {
                if(a[j]<a[i])
                {
                    int t=a[j];
                    a[j]=a[i];
                    a[i]=t;
                }
            }
        }
        Scanner scanner=new Scanner(System.in);
        System.out.println("输入一个整数,判断该整数是否在数组中");
        int num=scanner.nextInt();
        int count=0;
        end=N;mid=(end+start)/2;
        while(num!=a[mid])       //折半查找
        {
            if(num>a[mid])
                start=mid;
            else if(num<a[mid])
                end=mid;
            mid=(end+start)/2;
            count++;
            if(count>N/2)
                break;
        }
        if(count>N/2)
            System.out.println(num+"不在数组中");
        else
            System.out.println(num+"在数组中");
    }
    
}

你可能感兴趣的:(JAVA)