当前位置:网站首页>二分查找(折半查找)总结
二分查找(折半查找)总结
2022-06-10 00:06:00 【6映辰】
**
二分查找(折半查找)总结
**
一、基本概念
二分查找也叫折半查找,是一种效率比较高的查找方法。但是使用它有个前提:必须是采用顺序存储的线性表,表中按关键字有序排列,一般情况为按数值从小到大排列。
折半查找的过程为:
- 从表的中间记录开始,将查找值与其比较,如果相等则查找结束
- 如果中间值小于查找值,则查找值一定在表的后一半区间里,于是将左值设置为中间位置的下一个
- 如果中间值大于查找值,则查找值一定在表的前一半区间里,于是将右值设置为中间位置的前一个
- 设置完成后,继续从新区间的中间值开始比较,即继续第一步的内容直至查找完成
- 如果没有查找到,则返回-1
二、编写代码
1.二分查找
int BinarySearch(int arr[],int len,int key)
{
int left,mid,right;
left=0;
right=len;
while(left<=right)
{
mid=(left+right)/2;
if(arr[mid]<key) left=mid+1;
else if(arr[mid]>key) right=mid-1;
else break;
}
if(left<=right) return mid;
else return -1;
}
2.测试代码
#include <stdio.h>
int BinarySearch(int arr[],int len,int key)
{
int left,mid,right;
left=0;
right=len;
while(left<=right)
{
mid=(left+right)/2;
if(arr[mid]<key) left=mid+1;
else if(arr[mid]>key) right=mid-1;
else break;
}
if(left<=right) return mid;
else return -1;
}
int main()
{
int testArr[]={
3,6,9,16,21,29,56,67,89,99};
int len=sizeof(testArr)/sizeof(testArr[0])-1;
printf("%d\n",BinarySearch(testArr,len,67));//查找到
printf("%d",BinarySearch(testArr,len,0));//未查找到
return 0;
}
三、输出结果
可以看到:
- 查找到结果时,输出数组下标
- 未查找到时,输出-1
四、总结评价
二分查找的过程也可以用二叉树来描述,树中每个结点对应表中一个数据,但是结点不是记录的关键字,而是记录在表中的数组下标。由此得到的二叉树称为二分查找的判定树。
二分查找的优缺点:
- 比较次数少,查找效率高
- 只能适用于顺序存储结构的线性表
二分查找不适用于数据元素经常变动的线性表
有问题欢迎各位大佬指出
算法系列将持续更新,欢迎关注,一起学习
边栏推荐
- June 10, 2022 Daily: Huawei's top ten inventions were announced: efficient addition network and multi-objective game intelligent driving won the prize
- Sarsa
- POI exporting Excel
- On chip variation (OCV) concept learning
- Q-learning
- Pta7-5 Sina Weibo hot topics
- Illustration Google V8 06: prototype chain: how does V8 implement object inheritance?
- 478. randomly generate points in a circle
- FlinkSQL 之乱序问题
- University of Ulm, Germany | comparative characterization of 3D protein structure
猜你喜欢
随机推荐
Aquanee will land in gate and bitmart in the near future, providing a good opportunity for low-level layout
网络状态的起起伏伏
[input] only numbers can be input for verification
可重复读隔离级别的基石MVCC机制
编程中的In-place operation(就地操作)是什么意思?
电力系统北斗时钟同步系统的组成和配置
732. 我的日程安排表 III
Basic and introductory knowledge for PHP learning
typora 基本使用和更换typora的主题样式
POI exporting Excel
Retrofit2.0 method summary of adding header
The problem of connecting the computer to the printer (the printer display is not specified) solution
低边驱动和高边驱动
Do your filial duty to make an old people's fall prevention alarm system for your family
Illustration Google V8 06: prototype chain: how does V8 implement object inheritance?
Is it necessary to get PMP?
MySQL execution plan
IDC fait autorité pour prédire que l'industrie manufacturière chinoise est sur le point de monter dans le nuage
The cornerstone mvcc mechanism of repeatable read isolation level
Automatically open personal when opening xlsx file Xlsb table file









