当前位置:网站首页>折半查找
折半查找
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.运行结果
边栏推荐
- 初探JuiceFS
- Alibaba's latest summary 2022 big factory interview real questions + comprehensive coverage of core knowledge points + detailed answers
- Implement custom spark optimization rules
- 【剑指offer】面试题51:数组中的逆序对——归并排序
- QT (IV) mixed development using code and UI files
- 【剑指offer】面试题46:把数字翻译成字符串——动态规划
- Photoelectric isolation circuit design scheme (six photoelectric isolation circuit diagrams based on optocoupler and ad210an)
- HaoChen CAD building 2022 software installation package download and installation tutorial
- Network equipment hard core technology insider router Chapter 18 dpdk and its prequel (III)
- Problem solving in magic tower project
猜你喜欢

【剑指offer】面试题42:连续子数组的最大和——附0x80000000与INT_MIN

Spark TroubleShooting整理

3.3-5v conversion

Leetcode-1737- minimum number of characters to change if one of the three conditions is met

Watermelon book machine learning reading notes Chapter 1 Introduction

Spark 任务Task调度异常分析

MLX90640 红外热成像仪测温传感器模块开发笔记(七)

使用Lombok导致打印的tostring中缺少父类的属性

What format is this data returned from the background

【剑指offer】面试题54:二叉搜索树的第k大节点
随机推荐
“router-link”各种属性解释
Spark 3.0 Adaptive Execution 代码实现及数据倾斜优化
Leetcode 341. flattened nested list iterator DFS, stack / medium
$router.back(-1)
Leetcode 240. search two-dimensional matrix II medium
Use deconstruction to exchange the values of two variables
Four kinds of relay schemes driven by single chip microcomputer
multimap案例
Spark Bucket Table Join
Unity's simplest object pool implementation
JS uses for in and for of to simplify ordinary for loops
后台返回来的是这种数据,是什么格式啊
聊聊面试必问的索引
What format is this data returned from the background
Complexity analysis
Explanation of various attributes of "router link"
学习Parquet文件格式
With just two modifications, apple gave styleganv2 3D generation capabilities
EMC design scheme of USB2.0 Interface
Spark RPC