【C语言】 折半查找
程序员文章站
2024-03-20 18:50:34
...
#include<stdio.h>
#define M 10
int my_binsearch(int x, int v[], int n) // 带查找元素x,已排序数组v,数组元素个数
{
int left, right, mid;
left = 0, right = n - 1;
while (left <= right)
{
mid = (left + right) / 2;
if (x < v[mid])
{
right = mid - 1;
}
else if (x > v[mid])
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int v[M];
int i,x,ret;
char c;
printf("请输入一组有序的数:");
for (i = 0; i < M; i++)
{
scanf_s("%d", &v[i]);
}
flag:
printf("请输入要查找的数:");
scanf_s("%d", &x);
ret = my_binsearch(x, v, M); //ret接收函数返回值
if (ret != -1) //根据返回值做判断
{
printf("找到了!数%d在数组的第%d位\n", x, ret + 1);
}
else // 没有找到继续找
{
printf("没有找到!");
printf("\n是否继续查找?(Y/N)");
scanf_s("%c", &c);
getchar(c);
printf("\n");
while (c = 'Y') //可直接进行goto语句,我这样写为了重新查找时更清晰
{
goto flag;
}
}
system("pause");
return 0;
}
转载于:https://blog.51cto.com/survive/1705041