二分查找法

2021-12-16 19:27
110
0
添加收藏

二分查找法

前置条件为

有序数组

无重复元素

// 递归查询
public static int searchTargetIndex1(int[] arr, int target, int leftIndex, int rightIndex) {
        if (leftIndex == 0 && rightIndex == 0) {
            leftIndex = 0;
            rightIndex = arr.length - 1;
        }

        while (leftIndex <= rightIndex) {
            int middleIndex = (leftIndex + rightIndex) / 2;
            if (arr[middleIndex] > target) {
                return searchTargetIndex1(arr, target, leftIndex, middleIndex - 1);
            } else if (arr[middleIndex] < target) {
                return searchTargetIndex1(arr, target, middleIndex + 1, rightIndex);
            } else {
                return middleIndex;
            }
}

全部评论