其他分享
首页 > 其他分享> > 二分查找

二分查找

作者:互联网

class Solution {
    /**
     * 递归的二分查找
     * @param nums
     * @param target
     * @param left
     * @param right
     * @return
     */
    public int binarySearch(int[] nums, int target, int left, int right) {
        if(left > right) {
            return -1;
        }
        int midIndex = (int)(left + right) / 2 ;
        if(target > nums[midIndex]) {
            return binarySearch(nums, target, midIndex+1, right);
        } else if(target < nums[midIndex]) {
            return binarySearch(nums, target, left, midIndex-1);
        } else {
            return midIndex;
        }
    }

    /**
     * 非递归实现
     * @param nums
     * @param target
     * @return
     */
    public int binarySearchWithoutRecursion(int[] nums, int target) {
        int low = 0;
        int hight = nums.length -1;
        while(low <= hight) {
            int mid = (int) (low + hight) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(target < nums[mid]){
                hight = mid -1;
            } else {
                low = mid + 1;
            }
        }

        return -1;

    }
}

标签:二分,return,target,nums,int,param,midIndex,查找
来源: https://blog.51cto.com/janephp/2377440