java 二分查找算法
在已知数组内查找指定数值的索引坐标,以及打印出查找轮询次数。
public static void main(String[] args) {
Integer[] intNums = new Integer[1000];
for (int i = 1; i <= 1000; i++) {
intNums[i - 1] = i;
}
int findNum = 919;
int midNum = 0;
int leftIndex = 0;
int rightIndex = intNums.length;
int midIndex = 0;
int runnum = 0;
while (true) {
runnum++;
midIndex = ((leftIndex + rightIndex) / 2);
midNum = intNums[midIndex];
if (midNum < findNum) {
leftIndex = midIndex + 1;
} else if (midNum > findNum) {
rightIndex = midIndex - 1;
} else if (midNum == findNum) {
System.out.println("midIndex = " + midIndex);
System.out.println("runnum = " + runnum);
break;
} else if (leftIndex > rightIndex) {
System.out.println("error");
break;
}
}
}