当前位置:网站首页>Cow attracts the sword refers to the offer of binary search
Cow attracts the sword refers to the offer of binary search
2022-08-05 17:00:00 【The king of code!】

前言:
Encounter with Niu Ke:
一次偶然的机会我接触到了牛客网,From that time, I found that Niuke.com seems to be an all-around website,There are exercises in various languages、算法题、大厂的面试题、There are also functions such as job hunting.Since then, I have started my cattle journey.
I'll put the link here for those who need it to pick it up注册即可免费刷题
目录
二分查找
题目:

三个示例

问题描述
二分查找又称为折半查找,它要求待查找的数据元素必须是按关键字大小有序排列的.给定已排好序的n个元素s1,…,sn,现要在这n个元素中找出一特定元素x. 首先较容易想到使用顺序查找方法,逐个比较s1,…,sn,直至找出元素x或搜索遍整个序列后确定x不在其中.显然,该方法没有很好地利用n个元素已排好序这个条件.因此,在最坏情况下,顺序查找方法需要O(n)次比较.
算法思想
假定元素序列已经由小到大排好序,将有序序列分成规模大致相等的两部分,然后取中间元素与特定查找元素x进行比较,如果x等于中间元素,则算法终止;如果x小于中间元素,则在序列的左半部继续查找,即在序列的左半部重复分解和治理操作;否则,在序列的右半部继续查找,即在序列的右半部重复分解和治理操作.可见,二分查找算法重复利用了元素间的次序关系.
构造实例

代码实现
1、递归
//递归二分查找算法
int twoFind3(int A[], int k, int low, int high)
{
int middle;
if (low > high) return -1;//递归结束条件
middle = (low + high) / 2;
if (low==high && A[middle] == k) return middle;
if (low < high) {
if (A[middle] < k) return twoFind3(A, k, middle + 1, high);
else if(A[middle]==k) return middle;
else return twoFind3(A, k, 0, middle - 1);
}
return -1;
}2、非递归
int twoFind2(int A[], int len, int K)
{
int low = 0, high = len - 1,middle;
if (low > high) return -2;
while (low < high)//不含等于的情况,并在最后做判断
{
middle = (low + high) / 2;
if (K == A[middle]) return middle;
else if (K > A[middle]) low = middle + 1;
else high = middle - 1;
}
if (low == high && A[low] == K) return low;
return -1;
}时间复杂度

写在最后:If there are any errors or inadequacies in the article,欢迎各位指正.
边栏推荐
- 详解Oracle DELETE和TRUNCATE 的区别
- 不能不知道的excel实用操作技巧!
- 机器人强化学习——COCOI: Contact-aware Online Context Inference for Generalizable Non-planar Pushing(21 ICRA)
- Visual Studio Code如何新建一个工程
- MYSQL(进阶篇)——一篇文章带你深入掌握MYSQL
- 【案例】animation动画曲线之steps的使用
- 基于ABP和Magicodes实现Excel导出操作
- 8.lnmp architecture
- 2022 第四周全球 AI 模型周报
- 【C语言】通讯录(动态版+文件版)
猜你喜欢

面向动态图的极低时延 GNN 在线推理采样服务

【工具】简道云零代码开发平台

Cholesterol-PEG-Acid,Cholesterol-PEG-COOH,疏水性分子胆固醇-聚乙二醇-羧基

基于eureka-server的服务注册与消费案例

Visual Studio Code如何新建一个工程

解决FileZilla 报错“无法和 SFTP 服务器建立 FTP 连接,请选择合适的协议”

Ali's million-level Redis booklet shocked open source, opening up a new world of source code

What is Common Defect Enumeration (CWE)

使用Stream多年,collect还有这些“骚操作”?

Stored Procedure && Trigger
随机推荐
【知识科普】激光雷达(LiDAR)点云数据知多少?
TABLE
阿里百万级Redis小册震撼开源,打开源码新世界
五个方法,破解数据分析的核心难题
借生态力量,openGauss突破性能瓶颈
解决FileZilla 报错“无法和 SFTP 服务器建立 FTP 连接,请选择合适的协议”
【C语言】通讯录(动态版+文件版)
小型企业CIO为大型企业IT负责人提供的重要经验
安装特定指定版本 低版本的r包 r包降级
跨越“S型曲线”,华胜天成如何在数字时代开启第二曲线?
likeshop搭建商城系统,一步到位
MYSQL(进阶篇)——一篇文章带你深入掌握MYSQL
电脑重装系统桌面图标变成白色文件怎么恢复?
Sentinel link mode rule not working
疏水18碳磷脂磷脂-聚乙二醇-羧基,DSPE-PEG-Acid,CAS:1403744-37-5
每日一题(1)—— 最大连号
Cholesterol-PEG-Azide,CLS-PEG-N3,脂溶性胆固醇-聚乙二醇叠氮
Good code in the eyes of a compiler engineer: Loop Interchange
【 背包九讲——完全背包问题】
mapping transferdata FindTransferAnchors TransferData