#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int binary_search(int num, int *a, int lenth)
{
int left = 0;
int right = lenth;
int f;
while (left < right)
{
f = left + (right - left) / 2;
if (num > a[f])
{
left = f + 1;
}
else
if (num < a[f])
{
right = f - 1;
}
else
if (num == a[f])
return f;
}
if (left == right)
{
return -1;
}
}
int main()
{
int a[] = { 12, 14, 15, 16, 17, 18, 19, 21, 23, 24, 25, 57 };
int num, r;
int L = sizeof(a) / sizeof(a[0]) - 1;
printf("请输入您要找的数:");
scanf("%d", &num);
r = binary_search(num, a, L);
if (r == -1)
{
printf("没有找到\n");
}
else
printf("找到了:%d\n", r);
system("pause");
return 0;
}
在整型有序数组中查找想要的数字,找到了返回下标,找不到返回-1.(折半查找)
最新推荐文章于 2021-11-07 15:58:43 发布