public class ArrayTest3 {
// 数组的查找操作
public static void main(String[] args) {
int[] arr = { 1, 2, 4, 6, 9, 12, 15 };
int x= getIndex(arr,4);
System.out.println("x="+x);
int y = halfSearch(arr, 2);
System.out.println("y="+y);
int z = halfSearch_1(arr,2);
System.out.println("z="+z);
}
public static int getIndex(int[] arr, int key) {
for (int x = 0; x < arr.length; x++) {
if (arr[x] == key)
return x;
}
return -1;
}
// 折半查找
public static int halfSearch(int[] arr, int key) {
int min=0,max=arr.length - 1,mid=(min + max) / 2;
while (arr[mid] != key) {
if (key > arr[mid]) {
min = mid + 1;
} else if (key < arr[mid]) {
max = mid - 1;
}
if (mid > max) {
return -1;
}
mid = (min + max) / 2;
}
return mid;
}
//折半第二种方法
public static int halfSearch_1(int[] arr, int key) {
int min = 0, max = arr.length - 1, mid;
while (min <= max) {
mid = (max + min) >> 1;
if (key > arr[mid]) {
min = mid + 1;
} else if (key < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}
}
看过毕老师关于数组查找操作的视频后按老师的代码写的,通过折半查找数组中的元素2,正常应该是y=1,可为什么运行之后y=-1,麻烦各位大神给看下哪里错了,谢谢
|
|