当前位置:网站首页>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 
边栏推荐
- [acwing] explanation of the 57th weekly competition
- Principle of printf indefinite length parameter
- ZABBIX supports nail alarm
- Cloud native (30) | kubernetes' app store Helm
- Does Xinhua San still have to rely on ICT to realize its 100 billion enterprise dream?
- To understand again is the person in the song
- Interviewer: do you understand redis' shared object pool?
- 内网学习笔记(8)
- Journal quotidien des questions (6)
- 这是什么空调?
猜你喜欢
随机推荐
C语言 函数指针与回调函数
Stack calculation (whether the order of entering and leaving the stack is legal) - Code
OpenHGNN发布0.3版本
思考的角度的差异
PLM还能怎么用?
快讯:华为启动鸿蒙开发者大赛;腾讯会议发布“万室如意”计划
l六月集训(第27天) —— 图
How to choose LAN instant messaging software
手把手教你搭一个永久运行的个人服务器!
深入理解位运算
Implementation of recruitment website based on SSM
scrapy
With the advent of the era of Internet of everything, Ruijie released a scenario based wireless zero roaming scheme
Hue new account error reporting solution
jvm 参数设置与分析
每日刷题记录 (六)
Two TCP flow control problems
每日刷題記錄 (六)
一道shell脚本的统计题
如何使用200行代码实现Scala的对象转换器









