美文网首页
二分查找

二分查找

作者: emperorxiaomai | 来源:发表于2021-12-14 20:57 被阅读0次

二分查找

package org.example;

public class BinarySearch {
    public static void main(String[] args) {
        int[] targetArray = {1, 3, 5, 9, 10, 100, 50, 49, 20};
        int target = 100;
        QuickSort.quickSortTwoDirections(targetArray, 0, targetArray.length - 1);
        System.out.println("result index is:" + binarySearch(targetArray, target));
        System.out.println("result index is:" + recurBinarySearch(targetArray, target, 0, targetArray.length - 1));
    }

    public static int binarySearch(int[] targetArray, int targetValue) {
        int result = -1;
        int low = 0;
        int high = targetArray != null ? targetArray.length - 1 : 0;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (targetArray[mid] == targetValue) {
                result = mid;
                break;
            }
            if (targetArray[mid] > targetValue) {
                high = mid - 1;
            }
            if (targetArray[mid] < targetValue) {
                low = mid + 1;
            }
        }
        return result;
    }

    public static int recurBinarySearch(int[] targetArray,int targetValue,int start,int end) {
        int mid = (start + end) / 2;
        if (targetArray[mid] == targetValue) {
            return mid;
        }
        if (targetArray[mid] < targetValue) {
            return recurBinarySearch(targetArray, targetValue, mid + 1, end);
        } else {
            return recurBinarySearch(targetArray, targetValue, start, mid - 1);
        }
    }
}

相关文章

网友评论

      本文标题:二分查找

      本文链接:https://www.haomeiwen.com/subject/bamyfrtx.html