import java.util.Scanner;
public class BinarySearch {
public static void main(String args []){
Scanner sc=new Scanner(System.in);
int startN=sc.nextInt();
int endN=sc.nextInt();
int search=(int)(Math.random()*(endN-startN+1)+startN);
int l=endN-startN+1;
int [] array=new int [l];
for(int i=0;i<l;i++){
array[i]=startN;
startN++;
}
int end=l-1,start=0,middle=0;
boolean found=false;
int time=1;
while(start<end&&!found){
middle=(end+start)/2;
if(array[middle]>search){
end=middle-1;
time++;
}else if(array[middle]<search){
start=middle+1;
time++;
}else{
if(time>1) {
System.out.println("The number is:" + search + "\n" + "It took " + time + " tries!");
found = true;
}else{
System.out.println("The number is:" + search + "\n" + "It took " + time + " try!");
found = true;
}
}
}
}
}

uj5u.com熱心網友回復:
應該是沒考慮到search=startN= array[0]的情況,最后end會等于0直接跳出的while回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/97497.html
標籤:Java相關
上一篇:我下載CentOS在自己電腦上安裝Linux出現了這個,有人知道怎么回事和怎么解決嗎?
下一篇:視頻管理系統
