二分查找

mac2024-01-26  43

二分查找

二分查找的算法思想:

如图所示:

代码:
public class Demo { public static void main(String[] args) { //查找思想:前提条件:数组元素必须有序; //二分查找:每次查找一半 int[] arr = {10, 20, 30, 50, 90, 100, 101, 300, 400}; int index = getIndex(arr, 90); System.out.println("索引是" + index); } //二分查找 private static int getIndex(int[] arr, int ele) { //定义这三个索引很重要; int minIndex = 0; int maxIndex = arr.length - 1; int centerIndex = (minIndex + maxIndex) / 2; while (minIndex <= maxIndex) { if (ele == arr[centerIndex]) { return centerIndex; } else if (ele > arr[centerIndex]) { minIndex = centerIndex + 1; } else if (ele < arr[centerIndex]) { maxIndex = centerIndex - 1; } //注意需要重新计算中间索引 centerIndex = (minIndex + maxIndex) / 2; } return -1; } }
最新回复(0)