/*
二分法查找
*/
public class binarySearch {
public static void main(String[] args) {
int[] arrs = { 1, 3, 5, 7, 9, 11, 13 };
System.out.println(getIndex(arrs, 1));
System.out.println(getIndex(arrs, 7));
System.out.println(getIndex(arrs, 13));
}
// 使用二分查找法查找下标
public static int getIndex(int[] arr, int value) {
int start = 0;
int end = arr.length;
int mid = (start + end) / 2;
while (start <= end) {
if (value < arr[mid]) {
end = mid - 1 ;
} else if (value > arr[mid]) {
start = mid + 1 ;
} else {
return mid;
}
mid = (start + end) / 2;
}
return -1; // 表示没有找到
}
}
你的mid的刚开始的时候执行了两次,这样会丢掉一些数据!!! |