当前位置:网站首页>折半查找
折半查找
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.运行结果
边栏推荐
- How to package AssetBundle
- JS find the maximum and minimum values in the array (math.max() method)
- Transactions_ Basic demonstrations and transactions_ Default auto submit & manual submit
- Leetcode 456.132 mode monotone stack /medium
- Huawei's general card identification function enables multiple card bindings with one key
- Network equipment hard core technology insider router Chapter 5 tompkinson roaming the network world (Part 1)
- Multi table query_ Exercise 1 & Exercise 2 & Exercise 3
- Network equipment hard core technology insider router Chapter 21 reconfigurable router
- JUC(JMM、Volatile)
- Google team launches new transformer to optimize panoramic segmentation scheme CVPR 2022
猜你喜欢

Adaptation verification new occupation is coming! Huayun data participated in the preparation of the national vocational skill standard for information system adaptation verifiers

C语言:动态内存函数

Spark 任务Task调度异常分析

EMC design scheme of RS485 interface

Selenium reports an error: session not created: this version of chromedriver only supports chrome version 81

Leetcode 240. search two-dimensional matrix II medium

Spark TroubleShooting整理

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

How to take satisfactory photos / videos from hololens

【剑指offer】面试题49:丑数
随机推荐
使用双星号代替Math.pow()
后台返回来的是这种数据,是什么格式啊
js使用一元运算符简化字符串转数字
C语言:三子棋游戏
Network equipment hard core technology insider router Chapter 5 tompkinson roaming the network world (Part 1)
Troubleshooting the slow startup of spark local programs
How to take satisfactory photos / videos from hololens
Selenium reports an error: session not created: this version of chromedriver only supports chrome version 81
【剑指offer】面试题39:数组中出现次数超过一半的数字
Some binary bit operations
js寻找数组中的最大和最小值(Math.max()方法)
EMC design scheme of CAN bus
【剑指offer】面试题42:连续子数组的最大和——附0x80000000与INT_MIN
Unity performance optimization ----- occlusion culling of rendering optimization (GPU)
Discussion on STM32 power down reset PDR
Network equipment hard core technology insider router Chapter 21 reconfigurable router
[正则表达式] 匹配分组
NPM install error unable to access
Leetcode 783. binary search tree node minimum distance tree /easy
JS uses unary operators to simplify string to number conversion