当前位置:网站首页>二分查找的理解
二分查找的理解
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,毕竟两个模板都是左闭区间。
边栏推荐
- ssm常用到的依赖
- 邱盛昌:OPPO商业化数据体系建设实战
- R语言计算data.table在一个分组变量的值固定的情况下另外一个分组变量下指定数值变量的均值
- 有趣的 LD_PRELOAD
- 1723. 完成所有工作的最短时间
- How to view, modify, and delete SSH
- "Upgrade strategy" of two new committers
- 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
- Google浏览器调试技巧
- Saturated! Can't future programmers work anymore?
猜你喜欢

Advanced Qt development: a preliminary study QT + OpenGL

Interesting LD_ PRELOAD

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

Google browser debugging skills

Gerrit+2触发Jenkins任务

Detailed explanation of shardingjdbc database and table

How to view, modify, and delete SSH

Unit sshd. service could not be found

selenium元素定位

Sudo of uabntu
随机推荐
R语言使用pdf函数将可视化图像结果保存到pdf文件中、使用pdf函数打开图像设备、使用dev.off函数关闭图像设备、自定义width参数和height参数指定图像的宽度和高度
写技术博客的意义
Cloud development kunkun chicken music box wechat applet source code
MIPS 通用寄存器 + 指令
[BSP video tutorial] stm32h7 video tutorial Issue 8: the last issue of the MDK theme, the new generation of debugging technologies event recorder and RTT, and using stm32cubemx to generate project tem
Sudo of uabntu
(四)Golang运算符
Male god goddess voting source code v5.5.21 voting source code
(5) Outputs and outputs
R语言使用epiDisplay包的aggregate.plot函数可视化每个子集的汇总统计信息(可视化基于单个分组下的阳性指标的概率值及其95%置信区间、基于折线图、仅仅适用于目标类别为二分类)
Quick start sweep crawler framework
R语言使用epiDisplay包的tabpct函数生成二维列联表并使用马赛克图可视化列联表(二维列联表、边际频数、以及按行、按列的比例)、自定义设置ylab参数设置Y轴的轴标签文本(y axis)
Microsoft Office MSDT代码执行漏洞(CVE-2022-30190)漏洞复现
Feedback compilation
Cicada mother talks to rainbow couple: 1.3 billion goods a year, from e-commerce beginners to super goods anchor
How to do a good job of testing in the company (do a good job of testing)
R语言使用plot函数可视化数据散点图,使用font.axis参数指定坐标轴刻度标签的字体类型为斜体字体(italic)
Guitar Pro tutorial how to set up a MIDI keyboard
Is the securities account opened by qiniu safe? Is it legal?
Nebula's practice of intelligent risk control in akulaku: training and deployment of graph model