s1.0 力扣之二分查找法

class BinarySearch
    {
        /// <summary>
        /// 查找方法
        /// </summary>
        /// <param name="nums">数据</param>
        /// <param name="target">目标值</param>
        /// <returns></returns>
        public int search(int[] nums, int target)
        {
            int len = nums.Length;
            int left = 0;
            int right = len - 1;
            //目标元素可能存在在区间 [left, right]
            while (left <= right)
            {
                //推荐的写法是 int mid = left + (right - left) / 2;
                int mid = (left + right) / 2;
                if (nums[mid] == target)
                {
                    return mid;
                }
                //如果中间小于目标
                else if (nums[mid] < target)
                {
                    // 目标元素可能存在在区间 [mid + 1, right]
                    left = mid + 1;
                }
                //如果中间大于目标
                else
                {
                    // 目标元素可能存在在区间 [left, mid - 1]
                    right = mid - 1;
                }
            }

            return -1;
        }
    }

在上图解:

 

posted @ 2021-12-16 14:53  KyrieYang  阅读(23)  评论(0编辑  收藏  举报