当前位置:网站首页>在一个有序数组中查找具体的某个数字(二分查找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;
}
运行结果

边栏推荐
- [turn] functional area division based on poi ()
- uniapp实现横向点击滑动菜单
- turbo编译码误码率性能matlab仿真
- Live classroom system 03 supplement model class and entity
- Simulation de modulation et de démodulation du signal CBOC basée sur MATLAB, sortie de corrélation, spectre de puissance et suivi de décalage de fréquence
- xlswriter - excel导出
- Kettle实现共享数据库连接及插入更新组件实例
- Monotonous stack!!!
- Smart headline: smart clothing forum will be held on August 4, and the whole house smart sales will exceed 10billion in 2022
- [interview frequency] cookies, sessions, tokens? Don't worry about being asked after reading it
猜你喜欢
随机推荐
动态规划-力扣
Supervisor installation and use
@Feignclient detailed tutorial (illustration)
idea一次启动多个项目
Exploration and practice of Ali multimodal knowledge atlas
[test platform development] XVII. The interface editing page realizes the drop-down cascade selection, and binds the module to which the interface belongs
supervisord安装使用
基于matlab的BOC调制解调的同步性能仿真,输出跟踪曲线以及不同超前滞后码距下的鉴别曲线
NVIDIA vid2vid paper reproduction
The accuracy of digital addition
Postgresql快照优化Globalvis新体系分析(性能大幅增强)
Feignclient utilise un tutoriel détaillé (illustration)
uniapp实现横向点击滑动菜单
The official redis visualization tool is coming. The needle doesn't poke
day18
Cloud native observability tracking technology in the eyes of Baidu engineers
基於matlab的CBOC信號調制解調仿真,輸出其相關性,功率譜以及頻偏跟踪
c语言:深度刨析const关键字
基于matlab的CBOC信号调制解调仿真,输出其相关性,功率谱以及频偏跟踪
raid homes and plunder houses!









