当前位置:网站首页>二分查找的理解
二分查找的理解
2022-06-12 17:15:00 【老油条666】
常见的二分模板:
模板一,区间是左闭右闭的,即查找区间是[l,r]
int binary_search(int l, int r, int a[], int x) //返回值是元素x在数组a中的位置(下标)
{
int mid = 0;
while(l <= r)
{
mid = (l+r) >> 1;
if(a[mid] == x)
return mid;
if(a[mid] < x)
l = mid+1;
else
r = mid-1;
}
return -1;
}模板二,区间是左闭右开的,即查找区间是[l,r),老外喜欢玩这个,然后整个STL基本都是这种左闭右开的。
int binary_search(int l, int r, int a[], int x)
{
int mid = 0;
while(l < r)
{
mid = (l+r) >> 1;
if(a[mid] == x)
return mid;
if(a[mid] < x)
l = mid+1;
else
r = mid ;
}
return -1;
}注意这两个模板的区别,如果是左闭右闭的,while循环处应该是可以l == r的,然后在更新r的时候要将r赋值为mid-1,因为查找子区间也应该是左闭右闭的区间(因为mid在本次查找的时候已经查过了,所以子区间划分的时候mid不应该在区间中)。
如果是左闭右开的模板,则在更新的时候r要赋值为mid,这样才能保证查找子区间的时候也是左闭右开的。
l更新的时候始终是mid+1,毕竟两个模板都是左闭区间。
边栏推荐
- A variety of Qt development methods, which do you choose?
- 邱盛昌:OPPO商业化数据体系建设实战
- Fiddler抓包几种常用功能介绍(停止抓包、清空会话窗内容、过滤请求、解码、设置断点......)
- 记录使用yolov5进行旋转目标的检测
- (6) Control statement if/else switch
- Advanced Qt development: a preliminary study QT + OpenGL
- Yyds dry goods inventory leetcode question set 911 - 920
- 使用GCC的PGO(Profile-guided Optimization)优化整个系统
- 龙芯处理器内核中断讲解
- Atlas conflict Remote Code Execution Vulnerability (cve-2022-26134) vulnerability recurrence
猜你喜欢

Saturated! Can't future programmers work anymore?

Microsoft Office MSDT Code Execution Vulnerability (cve-2022-30190) vulnerability recurrence

Download PHP source code of leaf sharing station

rolabelImg的安装使用

使用GCC的PGO(Profile-guided Optimization)优化整个系统

龙芯处理器内核中断讲解

Male god goddess voting source code v5.5.21 voting source code

Volcano engine held a video cloud technology force summit and released a new experience oriented video cloud product matrix

I heard that distributed IDS cannot be incremented globally?

Selenium element positioning
随机推荐
How to use the official documents of pytorch and torchvision
Operating with idle funds
Picture online collection and delivery system source code
Analysis of CA certificate with high value
The R language uses the aggregate The plot function visualizes the summary statistical information of each subset (visualization is based on the probability value and its 95% confidence interval of th
php 实现无限极分类树(递归及其优化)
C # final review programming question (guessed by the teacher)
Exclusive interview with oppo find X5 Product Manager: deeply cultivate self-developed chips to create the ultimate flagship experience with the highest standards
Record the use of yolov5 to detect rotating targets
Flink 维表异步查询的实现以及问题排查
Volcano engine held a video cloud technology force summit and released a new experience oriented video cloud product matrix
性能优化之编译优化
"Upgrade strategy" of two new committers
The significance of writing technology blog
ssm常用到的依赖
(五)输出和输出
R语言使用ggplot2可视化dataframe数据中特定数据列的密度图(曲线)、并使用xlim参数指定X轴的范围
Pat class a 1139 first contact
邱盛昌:OPPO商业化数据体系建设实战
AlibabaProtect.exe如何删除、卸载