⼆分法c语⾔代码(递归、迭代)递归代码如下:
include <stdio.h>
int BSearch(int d[], int target, int low, int high)
{//第⼆个参数是要的数,返回下标
if (low <= high)
{
int m = (low + high) / 2;
if (target < d[m])
return BSearch(d, target, low, m - 1);
else if (target>d[m])
return BSearch(d, target, m + 1, high);
else
return m;
递归函数c语言规则}
return -1;
}
void main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 2000, 5000, 9999 };
int c = BSearch(a, 2000, 0, 13);
printf_s("c:%d\n", c);
getchar();
}
迭代代码如下:
#include <stdio.h>
int BSearch(int d[], int target, int low, int high)
{//第⼆个参数是要的数,返回下标
int m;
while (low <= high)
{
m = (low + high) / 2;
if (target < d[m])
high = m - 1;
else if (target>d[m])
low = m + 1;
else
return m;
}
return -1;
}
void main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 2000, 5000, 9999 };
int c = BSearch(a, 2000, 0, 13);
printf_s("c:%d\n", c);
getchar();
}
代码思路很简单,在此不再说明!!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论