编写折半查找函数
程序:
#include <stdio.h>
int binsearch(int x, int arr[], int len)//binsearch 折半,对分
{
int left = 0;
int right = len - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] < x)
{
left = mid + 1;
}
else if (arr[mid] == x)
{
return mid;
}
else
{
right = mid - 1;
}
return -1;
}
}
int main()
{
int arr[] = { 1, 21, 33, 46, 5, 62, 70, 81, 99, 10 };
int num = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
printf("请输入一个数:");
scanf("%d", &num);
int ret = binsearch(num, arr, sz);
if (ret == -1)
{
printf("not exist\n");
}
else
{
printf("数的位置:%d\n", ret + 1);
}
return 0;
}
结果一:
请输入一个数:81
数的位置:8
请按任意键继续. . .
结果二:
请输入一个数:83
not exist
请按任意键继续. . .