基本的二分查找(寻找一个数)
即搜索一个数,如果存在,返回其索引,否则返回 -1。
int binarySearch(int[] nums, int target)
{
int left = 0;
int right = nums.length - 1;
while(left <= right)
{
int mid = (right + left) / 2;
if(nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid - 1;
}
return -1;
}