int BinSearch(int a[], int n, int k)
{
int low, high, mid,
find, i;
find = 0;
low = 1;
high = n;
while (low <= high &&
!find)
{
mid = (low + high)/2;
if (a[mid] < k)
low = mid + 1;
else if (a[mid] > k)
high = mid - 1;
else
{
i = mid;
find = 1;
}
}
if (!find)
i = 0;
return i;
}
折半查找必须满足两个条件:一,元素必须是连续存储;二,元素必须有序。
Copyright 2011-2020 © MallocFree. All rights reserved.