当前位置:网站首页>Find a specific number in an ordered array (binary search or half search)
Find a specific number in an ordered array (binary search or half search)
2022-07-23 15:19:00 【Poplar 0】
Dichotomy search
Specific ideas
Binary search only applies to An increasing or decreasing array , Here we are unified as an increasing array , below , Let's briefly introduce the specific idea of binary search . Give the following array {1,2,3,4,5,6,7,8,9,10}. Their subscript is 0~9, We need to find in this set of arrays Numbers 7. First search for , The average value of the sum of the leftmost and rightmost subscripts is 4, We locked the number 5, because 5 Than 7 Small , So the number we are looking for can only be 5 To the right of ,5 The number on the left can be ignored . Second search , Numbers 6 And number 10 The average value of the sum of subscripts of is 7, We locked the number 8, because 8 Than 7 Big , So the number you are looking for can only be 8 Left side . Then we go on The third search …… Find the number 7 In the process of , We only used four searches , It can be seen that the efficiency is much higher than ordinary search .

Code implementation
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(" eureka , The subscript is %d\n", mid);
break;
}
}
return 0;
}
Running results

边栏推荐
猜你喜欢
![[machine learning basics] unsupervised learning (5) -- generation model](/img/a3/8b72d5472ceacdc094880be6efcbe4.png)
[machine learning basics] unsupervised learning (5) -- generation model

Redis bloom filter

IDEA 提高效率的5大免费插件

Selenium in the crawler realizes automatic collection of CSDN bloggers' articles

基於matlab的CBOC信號調制解調仿真,輸出其相關性,功率譜以及頻偏跟踪

Kettle實現共享數據庫連接及插入更新組件實例

The best time to buy and sell stocks

基于simulink的双闭环矢量控制的电压型PWM整流器仿真

How to realize 485 wireless communication between multiple sensors and Siemens PLC?

易基因|靶基因DNA甲基化测序(Target-BS)
随机推荐
turbo编译码误码率性能matlab仿真
VSCode 更新后与tab相关快捷键无法使用
centos7 中彻底卸载mysql
MySQL 常用命令
基于matlab的BOC调制信号捕获仿真
【HiFlow】定期发送腾讯云短信发送群
Use of RSA encryption
【机器学习基础】无监督学习(5)——生成模型
Simulation of voltage source PWM rectifier with double closed loop vector control based on Simulink
PostgreSQL has no NVL solution. PostgreSQL queries all tables
Chapter 4 use%rest API classes create rest services
安全作业7.22
智头条:智装论坛将于8月4日举行,2022全屋智能销售将破100亿
Russia hopes to effectively implement the "package" agreement on the export of agricultural products
开源四足机器人 附设计图及代码「建议收藏」
800V高压快充落地进程加快均胜电子获5亿欧元项目定点
BGP basic configuration
STL map attribute
Full backpack!
VSCode的感叹号+tab的快捷键不能用,以及A-SOUL-live2d插件出问题的解决方法