当前位置:网站首页>在一个有序数组中查找具体的某个数字(二分查找or折半查找)
在一个有序数组中查找具体的某个数字(二分查找or折半查找)
2022-07-23 10:36:00 【白杨0】
具体思路
二分查找只适用于递增或递减的数组,在这里我们统一为递增数组,下面,我们先来简单介绍一下二分查找的具体思路。给出下面一组数组{1,2,3,4,5,6,7,8,9,10}。它们的下标为0~9,我们要在这组数组中找到数字7。第一次查找,最左边和最右边的下标之和的平均值为4,我们锁定了数字5,因为5比7小,所以我们要找的数字只可能在5的右边,5左边的数字可以忽略了。第二次查找,数字6和数字10的下标之和的平均值为7,我们锁定了数字8,因为8比7大,所以要找的数字只可能在8的左边。接着又进行第三次查找……找到数字7的过程中,我们只用了四次查找,可以看出效率比普通查找高出不少。

代码实现
int main()
{
int arr[] = {
1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int right = sz - 1;
int k = 7;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else if (left = right)
{
printf("找到了,下标是%d\n", mid);
break;
}
}
return 0;
}
运行结果

边栏推荐
- 【OpenCV 例程200篇】225. 特征提取之傅里叶描述子
- NVIDIA vid2vid paper reproduction
- Live classroom system 02 build project environment
- [test platform development] XVII. The interface editing page realizes the drop-down cascade selection, and binds the module to which the interface belongs
- [turn] functional area division based on poi ()
- 面试官:生成订单30分钟未支付,则自动取消,该怎么实现?
- 什么是服务器托管及和虚拟主机的区别
- Live classroom system 01 database table design
- 7.13WEB安全作业
- leetcode: 17. 电话号码的字母组合
猜你喜欢

The official redis visualization tool is coming. The needle doesn't poke

【机器学习基础】无监督学习(5)——生成模型

读写锁ReadWriteLock还是不够快?再试试S…

Cloud native observability tracking technology in the eyes of Baidu engineers

Exploration and practice of Ali multimodal knowledge atlas

易基因|靶基因DNA甲基化测序(Target-BS)

General of MySQL_ Log log

raid homes and plunder houses!

真人踩过的坑,告诉你避免自动化测试常犯的10个错误

it 农民工的现状和历史
随机推荐
安全合理用电 收获清凉一“夏”
报错 | cannot read property ‘_normalized‘ of undefined
力扣-单调栈
Live classroom system 03 model class and entity
[test platform development] XVII. The interface editing page realizes the drop-down cascade selection, and binds the module to which the interface belongs
Selenium in the crawler realizes automatic collection of CSDN bloggers' articles
Getting started with Prometheus (III)
Live classroom system 02 build project environment
基于matlab的BOC调制解调的同步性能仿真,输出跟踪曲线以及不同超前滞后码距下的鉴别曲线
Activity的启动流程
上小学之前要学会的本领指引
读写锁ReadWriteLock还是不够快?再试试S…
Live classroom system 01 database table design
Dynamic planning - force buckle
The pit trodden by real people tells you to avoid the 10 mistakes often made in automated testing
易基因|靶基因DNA甲基化测序(Target-BS)
[heuristic divide and conquer] the inverse idea of heuristic merging
粒子边界碰撞的处理
go : gin Urlencoded 格式
Prometheus入门使用(三)