这是我第一次利用这个平台提问。我想知道下面的代码有什么问题,它们没有在main的末尾打印出目标数字的索引。怎么了?祝阅读这篇文章的人有一个美好的一天。
public class binarySearch {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int target,index;
int [] numArray={1,4,6,7,8,10,14,16,17,26,30,35,38,41};
System.out.print("What do you want to find?");
target=keyboard.nextInt();
index=binarySearch(numArray, target);
System.out.println("The element is found at index:"+index);
}
static int binarySearch(int [] numArray, int target){
int left=0;
int right=numArray.length-1;
int mid=(left+right)/2;
while(left<=right){
if(numArray[mid]==target){
return mid;
}else if(target<numArray[mid]){
right=mid-1;
}else{
left=mid+1;
}
}
return -1;
}
}
2条答案
按热度按时间gzjq41n41#
你没有重新计算,
mid
在循环内:oyxsuwqo2#
while条件后的初始中间值