当前位置:网站首页>对半查找(折半查找)
对半查找(折半查找)
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;
}
运行结果
边栏推荐
猜你喜欢

Bluetooth health management device based on stm32

Record number of visits yesterday

After the deployment is created, the pod problem handling cannot be created

What kind of air conditioner is this?

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

Esp32s3 iperf routine test esp32s3 throughput test

Today's sleep quality record 78 points

printf不定长参数原理

Configuration management center of microservices

硬件开发笔记(七): 硬件开发基本流程,制作一个USB转RS232的模块(六):创建0603封装并关联原理图元器件
随机推荐
【TcaplusDB知识库】TcaplusDB-tcapsvrmgr工具介绍(三)
Realization of hospital medical record management system based on JSP
不一样的习惯
与生活握手言和
Convn-n dimensional convolution
Airbnb double disk microservice
【动态规划】—— 背包问题
【医学分割】unet3+
What is low code for digital Nova? What is no code
《预训练周刊》第51期:重构预训练、零样本自动微调、一键调用OPT
[tcaplusdb knowledge base] Introduction to tcaplusdb tcapulogmgr tool (I)
dynamic programming
What kind of air conditioner is this?
How to open an account for CSI 500 stock index futures, what are the regular domestic stock index futures platforms, and where is the safest place to open an account?
[weekly replay] the 81st biweekly match of leetcode
Ali an interview question: use two threads to output letters and numbers alternately
Make learning pointer easier (2)
Nifi from introduction to practice (nanny level tutorial) - identity authentication
awk 简明教程
printf不定长参数原理