当前位置:网站首页>对半查找(折半查找)
对半查找(折半查找)
2022-06-27 13:09:00 【fitpolo】
//非递归方式解决
#include <stdio.h>
//返回下标
int binary_search(int *pdata,int size,int x)
{
int low,hight,mid;
low = 0;
hight = size-1;
while(low <= hight)
{
mid = (hight + low)/2;
if (pdata[mid] < x)
{
low = mid + 1;
}else if (pdata[mid] > x)
{
hight = mid - 1;
}else
{
return mid;
}
}
return -1;
}
//递归方法解决
//递归方法
int binary_search_recursion(int *pdata,int hight,int low,int x)
{
int mid=0;
if (low > hight)
{
printf("-1hight;%d-low:%d\r\n",hight,low);
return -1;
}
//printf("hight;%d-low:%d\r\n",hight,low);
mid = (hight + low)/2;
if (pdata[mid]<x)
{
binary_search_recursion(pdata,hight,mid + 1,x);
} else if (pdata[mid]>x)
{
binary_search_recursion(pdata,mid - 1,low,x);
}else
{
return mid;
}
}
//测试代码
int main(int argc, char *argv[])
{
int result;
#define BUF_SIZE 10
int buf[BUF_SIZE] = {
1,3,5,7,9,11,13,15,17,20};
//result = binary_search(buf,BUF_SIZE,20);
result = binary_search_recursion(buf,9,0,20);
printf("result:%d\r\n",result);
//result = binary_search(buf,BUF_SIZE,19);
result = binary_search_recursion(buf,BUF_SIZE-1,0,19);
printf("result:%d\r\n",result);
result = binary_search_recursion(buf,BUF_SIZE-1,0,1);
printf("result:%d\r\n",result);
return 0;
}
运行结果
边栏推荐
- Three traversal methods of binary tree
- A pang's operation record
- Postman如何设置成中文?(汉化)
- Privacy computing fat offline prediction
- dynamic programming
- How to close windows defender Security Center
- Prometheus 2.26.0 新特性
- awk 简明教程
- Size end byte order
- Threejs' ambient light + point light + parallel light + spherical light and Hepler understanding + shadow ()
猜你喜欢

Cool in summer

Airbnb double disk microservice

万物互联时代到来,锐捷发布场景化无线零漫游方案

隐私计算FATE-离线预测

Database Series: MySQL index optimization and performance improvement summary (comprehensive version)

Local visualization tool connects to redis of Alibaba cloud CentOS server
![[acwing] explanation of the 57th weekly competition](/img/ef/be89606b0e7fffac08280db0a73781.gif)
[acwing] explanation of the 57th weekly competition

GCC compiling dynamic and static libraries

Summary of redis master-slave replication principle

【医学分割】unet3+
随机推荐
POSIX AIO -- glibc 版本异步 IO 简介
新华三的千亿企业梦,还得靠吃ICT老本来实现?
[tcapulusdb knowledge base] Introduction to tcapulusdb tcapsvrmgr tool (III)
《预训练周刊》第51期:重构预训练、零样本自动微调、一键调用OPT
Three traversal methods of binary tree
Cloud native (30) | kubernetes' app store Helm
中证500股指期货怎么开户,国内正规的股指期货平台有哪些,在哪里开户最安全?
Firewall foundation Huawei H3C firewall web page login
局域网即时通讯软件应该怎么选择
【医学分割】unet3+
Deeply convinced plan X - system foundation summary
socket阻塞和非阻塞模式
To understand again is the person in the song
JSON. Stringify usage
外包2年的我终于上岸了!记录我的字节跳动3轮面试,希望帮助到大家!
Prometheus 2.26.0 新特性
与生活握手言和
Centos7命令行安装Oracle11g
实现WordPress上传图片自动重命名的方法
Hue new account error reporting solution