当前位置:网站首页>二分查找的理解
二分查找的理解
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,毕竟两个模板都是左闭区间。
边栏推荐
- R language calculates data Table specifies the mean value of a numeric variable when the value of one grouped variable is fixed and another grouped variable
- Alibaba cloud image station supports IPv6!
- R语言使用pdf函数将可视化图像结果保存到pdf文件中、使用pdf函数打开图像设备、使用dev.off函数关闭图像设备、自定义width参数和height参数指定图像的宽度和高度
- 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
- Flink 维表异步查询的实现以及问题排查
- 借助SpotBugs将程序错误扼杀在摇篮中
- 2080 virtual machine login command
- Saturated! Can't future programmers work anymore?
- Fiddler抓包几种常用功能介绍(停止抓包、清空会话窗内容、过滤请求、解码、设置断点......)
- Interesting LD_ PRELOAD
猜你喜欢

MySQL事务简介、事务隔离级别

Kill program errors in the cradle with spotbugs

快速入门scrapy爬虫框架

D. master router setting and 401 networking

goland变成中文版了怎么修改回英文版

Download PHP source code of leaf sharing station

Swintransformer network architecture

Cicada mother talks to rainbow couple: 1.3 billion goods a year, from e-commerce beginners to super goods anchor

Guitar Pro tutorial how to set up a MIDI keyboard

多种Qt的开发方式,你选择哪种?
随机推荐
Swintransformer network architecture
错误记录:IllegalStateException: Optional int parameter ‘xxxx‘ is
Yyds dry goods inventory leetcode question set 911 - 920
STL -- function object
Enterprise internal online training system source code
The safety of link 01 was questioned, and "ultra high strength" became "high strength"_ Publicity_ Steel_ problem
Is the securities account opened by qiniu safe? Is it legal?
(5) Outputs and outputs
Microsoft Office MSDT代码执行漏洞(CVE-2022-30190)漏洞复现
R语言使用epiDisplay包的tabpct函数生成二维列联表并使用马赛克图可视化列联表(二维列联表、边际频数、以及按行、按列的比例)、自定义设置ylab参数设置Y轴的轴标签文本(y axis)
分辨率与行场同步信号的关系 场消隐
qemu+gdb小节
(七)循环语句for
5-5配置Mysql复制 基于日志点的复制
淘宝Native研发模式的演进与思考 | DX研发模式
Record the use of yolov5 to detect rotating targets
selenium元素定位
C# 业务流水号规则生成组件
"Upgrade strategy" of two new committers
R language uses the sum function of epidisplay package to calculate the descriptive statistical summary information of the specified variables in dataframe under different grouped variables and visual