public static void main(String[] args){
//线性查找
boolean isFlag = true;
String dest = "GG";
for(int i = 0; i<arr.length;i++) {
if(dest.equals(arr[i])) {
System.out.println("找到了,位置在" + i);
isFlag = false;
break;
}
}
if(isFlag) {
System.out.println("没找到");
}
//二分法查找
//前提:所要查找的数组必须有序
int[] arr2 = new int[] {-53,-23,5,20,56,77,88,99,100,234};
boolean isFlag1 = true;
int dest1 = 56;
int head = 0;//初始首索引值
int end = arr2.length-1;//初始末索引值
while(head<=end) {
int middle = (head+end)/2;
if(dest1 == arr2[middle]) {
System.out.println("找到了,位置在" + middle);
isFlag1 = false;
break;
}else if(arr2[middle]>dest1) {
end = middle-1;
}else {
head = middle+1;
}
}
if(isFlag1) {
System.out.println("没找到");
}
}
线性查找、二分查找
最新推荐文章于 2024-08-24 22:01:16 发布