About Binary Search

about Binary Search 二分查找

普通的二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int BinarySearch_nonrecursive(vector<int>& nums, int target) {
int left = 0, right = (int)nums.size() - 1;
while (left <= right) { //不加 = 如果数组长度为1 会错
int mid = (left + right)/2;
if (nums[mid] > target) {
right = mid - 1;
}
else if (nums[mid] < target) {
left = mid + 1;
}
else return mid;
}
return 0;
}

1
2
3
4
5
6
7
8
9
//递归 
int BinarySearch_recursive(vector<int>& nums, int target, int left, int right) {
if (left > right) return 0;
int mid = (left + right) / 2;
if (nums[mid] > target) return BinarySearch_recursive(nums, target, left, mid - 1);
else if (nums[mid] < target) return BinarySearch_recursive(nums, target, mid + 1, right);
else return mid;

}

如果你只想要二分查找找到的第一个:

1
2
3
4
5
6
7
8
9
10
11
12
13
int BinarySearch_First_nonrecursive(vector<int>& nums, int target) { //查找第一个
int left = 0, right = (int)nums.size() - 1;
while (left <= right) {
int mid = (left + right)/2;
if (nums[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return nums[left] == target ? left : -1;
}
  • (l + r + 1) >> 1; 进阶的 (r - l)/2 + l;

About Binary Search
https://www.mementos.top/1976/04/01/about Binary Search 二分查找/
作者
Natsumi
发布于
1976年4月1日
许可协议