当前位置:网站首页>Half find (half find)
Half find (half find)
2022-06-27 13:29:00 【fitpolo】
// Non recursive solution
#include <stdio.h>
// Returns the subscript
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;
}
// Recursive solution
// Recursive method
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;
}
}
// Test code
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;
}
Running results
边栏推荐
- ENSP cloud configuration
- How to choose LAN instant messaging software
- 实现WordPress上传图片自动重命名的方法
- JVM parameter setting and analysis
- Prometheus 2.26.0 new features
- How to use 200 lines of code to implement Scala's Object Converter
- Airbnb复盘微服务
- Good luck today
- Make learning pointer easier (2)
- Local visualization tool connects to redis of Alibaba cloud CentOS server
猜你喜欢
浅谈软件研发的复杂性与效能提升之道
What kind of air conditioner is this?
创建Deployment后,无法创建Pod问题处理
Openfeign service interface call
Tiktok practice ~ public / private short video interchange
ThreadLocal 源码全详解(ThreadLocalMap)
Cesium realizes satellite orbit detour
IJCAI 2022 | 用一行代码大幅提升零样本学习方法效果,南京理工&牛津提出即插即用分类器模块
AGCO AI frontier promotion (6.27)
[medical segmentation] unet3+
随机推荐
Size end byte order
Tiktok practice ~ public / private short video interchange
crane:字典项与关联数据处理的新思路
With the advent of the era of Internet of everything, Ruijie released a scenario based wireless zero roaming scheme
To understand again is the person in the song
JVM parameter setting and analysis
MySQL 索引及其分类
mysql 锁机制与四种隔离级别
Realization of hospital medical record management system based on JSP
ensp云朵配置
IJCAI 2022 | greatly improve the effect of zero sample learning method with one line of code. Nanjing Institute of Technology & Oxford proposed the plug and play classifier module
快讯:华为启动鸿蒙开发者大赛;腾讯会议发布“万室如意”计划
Daily question brushing record (6)
After the deployment is created, the pod problem handling cannot be created
scrapy
思考的角度的差异
【Acwing】第57场周赛 题解
C语言 函数指针与回调函数
深信服X计划-系统基础总结
Does Xinhua San still have to rely on ICT to realize its 100 billion enterprise dream?