Home Article Practice 二分查找(输入一个数,输出位数,没有输出不存在)

二分查找(输入一个数,输出位数,没有输出不存在)

2021-07-25 15:29  views:387  source:135792468    

public static void main(String args[]){
int a[]={1,5,8,10,16,18,21,26};
Scanner scan = new Scanner(System.in);
int b = scan.nextInt();
int start = 0,end = a.length-1,middle = (start+end)/2;
while(start<=end){
if(b == a[middle]){
System.out.println(middle);
break;
}else if(b < a[middle]){
end = middle-1;
}else{
start = middle+1;
}
middle = (start+end)/2;
}
if(start>end){
System.out.println("不存在");
}
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)