package com.atguigu;public class Main { public static void main(String[] args) { //二分法查找 //前提:所查找的數組必須有序 int[] arr=new int[]{-98,-34,2,34,54,66,79,105 ...
package com.atguigu;
public class Main {
public static void main(String[] args) {
//二分法查找
//前提:所查找的數組必須有序
int[] arr=new int[]{-98,-34,2,34,54,66,79,105,210,333};
int dest=-3;
int head=0;//初始的首索引
int end=arr.length-1;
boolean isFlag=true;
while(head<=end){
int middle=(head+end)/2;
if(dest==arr[middle]){
System.out.println("找到指定的元素,位置為"+middle);
isFlag=false;
break;
}else if(arr[middle]>dest){
end=middle-1;
}else{
head=middle+1;
}
}
if(isFlag){
System.out.println("很遺憾,沒有找到");
}
}
}