当前位置:网站首页>折半查找
折半查找
2022-07-27 14:27:00 【发发是只呆头鹅】
1.折半查找
从已给的数组中查找某元素,每次都从中间查找,前提是数组是递增或递减的,效率较高。
2.原理
和数学中的二分法类似,将需要查找的元素和数组的中间元素比较,进过这一次比较就能排除一般的元素,然后再循环这个过程
3.代码实现
#include <stdio.h>
//折半查找
int BinarySearch(int arr[],int size,int e)
{
int left=0;
int right=size-1;
while(left<=right)
{
int mid=(left+right)/2; //这一句必须放在循环里面,因为每次循环left或right的值会变
if(arr[mid]>e)
right=mid-1;
else if(arr[mid]<e)
left=mid+1;
else
return mid;
}
if(left>right)
return -1; //当返回值为-1时,就是没找到,其他均为找到
}
int main()
{
int arr[]={
1,2,3,4,5,6,7,8,9};
int e=8; //要查找的元素
int size=sizeof(arr)/sizeof(arr[0]);
int ret=BinarySearch(arr,size,e);
if(ret!=-1)
printf("找到了!\n");
else
printf("没找到!\n");
return 0;
}
4.运行结果
边栏推荐
- C language: factorial recursive implementation of numbers
- Leetcode 191. number of 1 bits bit operation /easy
- Use deconstruction to exchange the values of two variables
- Fluent -- layout principle and constraints
- Pictures to be delivered
- The design method of integral operation circuit is introduced in detail
- [正则表达式] 匹配开头和结尾
- Network equipment hard core technology insider router Chapter 6 tompkinson roaming the online world (middle)
- 股票开户佣金优惠,炒股开户哪家证券公司好网上开户安全吗
- HaoChen CAD building 2022 software installation package download and installation tutorial
猜你喜欢

Spark Bucket Table Join

实体类(VO,DO,DTO)的划分

Complexity analysis

C语言:三子棋游戏

Spark TroubleShooting整理
![[daily question 1] 558. Intersection of quadtrees](/img/96/16ec3031161a2efdb4ac69b882a681.png)
[daily question 1] 558. Intersection of quadtrees

With just two modifications, apple gave styleganv2 3D generation capabilities

What format is this data returned from the background

Leetcode 781. rabbit hash table in forest / mathematical problem medium

Huayun data creates a perfect information technology and innovation talent training system to help the high-quality development of information technology and innovation industry
随机推荐
Implement custom spark optimization rules
Sword finger offer cut rope
The design method of integral operation circuit is introduced in detail
Explanation of various attributes of "router link"
js使用一元运算符简化字符串转数字
Use deconstruction to exchange the values of two variables
Leetcode interview question 17.21. water volume double pointer of histogram, monotonic stack /hard
How to package AssetBundle
【剑指offer】面试题49:丑数
[TensorBoard] OSError: [Errno 22] Invalid argument处理
Tools - common methods of markdown editor
Deveco studio2.1 operation item error
Dan bin Investment Summit: on the importance of asset management!
EMC design scheme of USB2.0 Interface
2022-07-27 Daily: IJCAI 2022 outstanding papers were published, and 298 Chinese mainland authors won the first place in two items
[系统编程] 进程,线程问题总结
设置提示框位置随鼠标移动,并解决提示框显示不全的问题
Multi table query_ Exercise 1 & Exercise 2 & Exercise 3
初识结构体
js寻找数组中的最大和最小值(Math.max()方法)