/******
递增数组元素的折半查找
*******/
#include <stdio.h>
#include <stdlib.h>
int binsearch(int x, int v[], int n) //数组一定是有序排列
{
int mid; //中间量
int left = 0;
int right = n - 1;
while (left < right)
{
mid = (right + left) / 2;
if (v[mid] > x)
{
right = mid - 1; //-1操作提高效率
}
else if (v[mid] == x)
{
return mid;
}
else
{
left = mid + 1;
}
}
}
int main(void)
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int ret = binsearch(8, arr, 9);
printf("%d\n",arr[ret]);
}
递增数组元素的折半查找
最新推荐文章于 2022-03-20 20:54:10 发布