题干
代码
class Solution {
public:
int search(vector<int>& nums, int target) {
int low=0,high=nums.size()-1;
while(low<=high){
// int mid=(low+high)/2;
int mid=low+(high-low)/2; // 防止溢出 等同于(left + right)/2
if(nums[mid]>target)
high=mid-1;
else if(nums[mid]<target)
low=mid+1;
else return mid;
}
return -1;
}
};
--------------------------2022/5/20 复习基本算法---------------------------------
非递归
public static int binarysearch2(int[] arr, int value) {
int left = 0, right = arr.length-1;
while (right >= left) {
int mid = (left + right) / 2;
if (value == arr[mid]) {
return mid;
}
if (value > arr[mid]) {
left = mid + 1;
}
if (value < arr[mid]) {
right = mid - 1;
}
}
return -1;
}
递归
/**
* 递归式二分查找
* @param arr
* @param left 左
* @param right 右
* @param digit 要找的数
* @return 找到的数的位置
*/
public static int binarysearch(int[] arr, int left, int right, int digit) {
int mid = (left + right) / 2;
// 找不到
if (right == left) {
System.out.println("递归式找不到!");
return -1;
}
if (digit > arr[mid]) {
return binarysearch(arr, mid + 1, right, digit);
}
if (digit < arr[mid]) {
return binarysearch(arr, left, mid - 1, digit);
}
if (digit == arr[mid]) {
return mid;
}
return mid;
}