public static void main(String[] args) {
int[] arr = new int[]{3, 5, 8, 10};
int find = 6;
int sIndex = 0;
int eIndex = arr.length - 1;
int fIndex = find(sIndex, eIndex, find, arr);
if (fIndex >= 0) {
System.out.println("找到了,index:" + fIndex);
} else {
System.out.println("没找到");
}
reverse();
}
// https://www.cnblogs.com/morethink/p/8379475.html
// 二分查找中mid值的计算方法 https://www.cnblogs.com/xjtsh/p/12614374.html
private static int find(int sIndex, int eIndex, int find, int[] arr) {
System.out.println("sIndex: " + sIndex + ", eIndex: " + eIndex);
if (sIndex > eIndex) { // 1:中断条件
return -1;
}
int mIndex = sIndex + (eIndex - sIndex) / 2; // 2:中间数的找法
System.out.println("mIndex: " + mIndex);
if (arr[mIndex] == find) {
return mIndex;
} else if (arr[mIndex] > find) {
return find(sIndex, mIndex - 1, find, arr);
} else {
return find(mIndex + 1, eIndex, find, arr);
}
}
网友评论