原理
一个数据有升序的数组,每次取中间元素比较,
如果大于需要查找的元素,则去后面数据,中间数据作为起点最后数据作为终点再定中间数据比较。
如果小于需要查找的数据,则取前面数据,起点不变中间数据作为终点再定中间数据比较。
代码
public static void main(String[] args) { int[] numArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}; int value = 10; int index = searchIndex(numArr, value); log.info("index: " + index); } /** * 查找索引 * * @param numArr * @param value * @return */ public static int searchIndex(int[] numArr, int value) { if (numArr == null || numArr[numArr.length - 1] < value) { return -1; } int firstIndex = 0; int middleIndex = numArr.length / 2; int lastIndex = numArr.length - 1; while (firstIndex < lastIndex) { if (numArr[middleIndex] == value) { return middleIndex; } if (numArr[middleIndex] > value) { lastIndex = middleIndex; } else { firstIndex = middleIndex; } middleIndex = (lastIndex + firstIndex) / 2; } return -1; }
标签:return,int,lastIndex,value,二分法,middleIndex,查找,numArr From: https://www.cnblogs.com/zhougongjin/p/17205709.html