算法之禅-二分查找

public int Search(int[] nums, int target) {
        int left = 0;
        int right = nums.Length - 1;
        while(left <= right)
        {
            int middle = left + (right - left)/2;
            if (nums[middle]>target)
            {
                right = middle - 1;
            }else if (nums[middle]<target)
            {
                left = middle + 1;
            }else
            {
                return middle;
            }
        }
        // 未找到目标值
        return -1;
    }
 
//注意中间值:left+(right-left)/2 = mid;
posted @ 2022-07-14 14:07  vba是最好的语言  阅读(39)  评论(0编辑  收藏  举报