转载自:https://www.jianshu.com/p/0f823fbd4d20

二分查找很好写,却很难写对,出错原因主要集中在判定条件和边界值的选择上,很容易就会导致越界或者死循环的情况。

下面对二分查找及其变形进行总结:

 

首先,二分查找的序列必须是有序的、有序的、有序的

 

如果环境允许,可以用库函数直接使用

 

二分查找的函数有 3 个: 参考:https://www.cnblogs.com/Tang-tangt/p/9291018.html

头文件是#include<algorithm>

 

lower_bound(起始地址,结束地址,要查找的数值) - 起始地址

 

upper_bound(起始地址,结束地址,要查找的数值) - 起始地址

 

binary_search(起始地址,结束地址,要查找的数值) 

 

说明:lower_bound()和upper_bound()返回的地址,都是从位置1开始算起的,[ first, last ),即first最小是从1开始的

 

1  函数lower_bound() 

 

功能:函数lower_bound()在[ first,last )区间进行二分查找,返回大于或等于val的第一个元素位置

 

注意:如果val不存在,则返回last+1的位置,位置last+1是越界的!!

 

 

 

2 函数upper_bound()

 

功能:函数upper_bound()在[ first,last )区间进行二分查找,返回大于val的第一个元素位置

 

注意:如果val刚好在上边界last的位置上,upper_bound()返回0;如果val不存在,则返回last+1的位置,而位置last+1是越界的!!

 

3 函数binary_search()

 

功能:判断查找的数是否存在,返回的是一个bool值

 

 

#include<iostream>
#include<algorithm>
using namespace std;
int a[1005];
int main()
{
  int n;
  cin>>n;
  for(int i=0;i<n;i++)
    cin>>a[i];
  sort(a,a+n);
  int x,y;
  cout<<binary_search(a,a+n,5)<<endl;
  x=upper_bound(a,a+n,5)-a;
  y=lower_bound(a,a+n,5)-a;
  cout<<a[x]<<endl;
  cout<<a[y]<<endl;
  return 0;

}
View Code

相关文章:

  • 2021-09-04
  • 2021-10-31
  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
  • 2022-12-23
  • 2021-08-04
  • 2021-11-25
猜你喜欢
  • 2022-01-18
  • 2022-12-23
  • 2022-02-19
  • 2021-06-18
相关资源
相似解决方案