二分查找:
在有序序列中查找,每次忽略一半
1 源文件
/*
测试用值:
15 20 32 46 57 77 89 133 456 966
*/
#include<stdio.h>
int halfFind(int* arr, int len, int data);
int main()
{
int arr[] = { 15 ,20 ,32 ,46 ,57 ,77 ,89 ,133 ,456 ,966 };
int n;
int r;
while (1)
{
printf("请输入要查找的值:");
scanf_s("%d", &n);
if (66666 == n)
break;
r = halfFind(arr, 10, n);
if (r >= 0)
{
printf("找到了%d,%d;\n", r, n);
}
else
{
printf("没找到\n");
}
}
return 0;
}
int halfFind(int* arr, int len, int data)
{
int right = len - 1;
int left = 0;
int mid = (right + left) / 2;
while (1)
{
if (arr[mid] == data)
return mid;
else if (arr[mid] < data)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
mid = (right + left) / 2;
if (left > right)break;
}
return -1;
}
|