二分查找是建立在有序的基础上的
基础模板
int bsearch(vector<int>& numbers, int value) {
int left=0, right = numbers.size()-1;
while(left <= right){ //有的写法这里是 < , 则条件结束时返回的需是 left 而非 -1
int mid = left + (right - left)/2;//防止溢出
if(numbers[mid] == value){
return mid;
}else if(numbers[mid] < value){
left = mid + 1;
}else{
right = mid - 1;
}
}
return -1;
}
变种
1.查找第一个值等于给定值的元素
int bsearch(vector<int>& numbers, int value) {
int left=0, right = numbers.size()-1;
while(left <= right){ //有的写法这里是 < , 则条件结束时返回的需是 left 而非 -1
int mid = left + (right - left)/2;//防止溢出
if(numbers[mid] < value){
left = mid + 1;
}else if(numbers[mid] > value){
right = mid - 1;
}else{
//1.值相等 2.前一个值不是value
if(mid==0 || numbers[mid-1]!=value){
return mid;
}else{
right = mid - 1;
}
}
}
return -1;
}
2.查找最后一个值等于给定值的元素
int bsearch(vector<int>& numbers, int value) {
int left=0, right = numbers.size()-1;
while(left <= right){ //有的写法这里是 < , 则条件结束时返回的需是 left 而非 -1
int mid = left + (right - left)/2;//防止溢出
if(numbers[mid] < value){
left = mid + 1;
}else if(numbers[mid] > value){
right = mid - 1;
}else{
//1.值相等 2.后一个值不是value
if(mid==numbers.size()-1 || numbers[mid+1]!=value){
return mid;
}else{
left = mid + 1;
}
}
}
return -1;
}
3.查找第一个值大于等于给定值的元素
int bsearch(vector<int>& numbers, int value) {
int left=0, right = numbers.size()-1;
while(left <= right){ //有的写法这里是 < , 则条件结束时返回的需是 left 而非 -1
int mid = left + (right - left)/2;//防止溢出
if(numbers[mid] < value){
left = mid + 1;
}else{
//1.>= 2.前一个值小于value
if(mid==0 || numbers[mid-1]<value){
return mid;
}else{
right = mid - 1;
}
}
}
return -1;
}
4.查找最后一个值小于等于给定值的元素
int bsearch(vector<int>& numbers, int value) {
int left=0, right = numbers.size()-1;
while(left <= right){ //有的写法这里是 < , 则条件结束时返回的需是 left 而非 -1
int mid = left + (right - left)/2;//防止溢出
if(numbers[mid] > value){
right = mid - 1;
}else{
//1.<= 2.后一个值大于value
if(mid==numbers.size()-1 || numbers[mid+1]>value){
return mid;
}else{
left = mid + 1;
}
}
}
return -1;
}