//折半查找(有序数列)
int BinSearch(int *a,int len,int key)
{
int low = 0;
int high = len-1;
int mid;
while(low<=high) //若为 while(low<high) (1)
{
mid = (low + high)/2;
if(a[mid]==key)
{
return mid;
}
else if(a[mid] < key)
{
low = mid+1; // 若low = mid (2)
}
else
{
high = mid-1; // 若high = mid (3) 则当i=6时,程序出现死循环
}
}
return -1;
}
int main()
{
int arr[] = {1,2,3,5,7,9,10};
int len = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i< len; i++)
{
printf("%d\n",BinSearch(arr,len,arr[i]));
}
printf("%d\n",BinSearch(arr,len,0));
printf("%d\n",BinSearch(arr,len,4));
printf("%d\n",BinSearch(arr,len,10));
return 0;
}
C | 折半查找法
最新推荐文章于 2022-11-03 20:44:43 发布