标签:二分法
二分法查找的时间复杂度最小,但是要求所查找的序列为有序序列
#include <stdio.h>
int bin_find(int* pa, int low, int high, int key)
{
int tmp = (low + high)/2;
if(low > high )
return -1;
else {
if(key > pa[tmp])
return bin_find(pa, tmp+1, high, key);
else if(key < pa[tmp])
return bin_find(pa, low, tmp-1, key);
else
return tmp;
}
}
int main()
{
int a[10] = {0,1, 2, 3, 4, 5, 6, 7, 8, 9};
int ret = bin_find(a, 0, 9, 3);
if(ret < 0){
printf("not found. \n");
return -1;
}
printf("a[%d]: %d\n",ret, a[ret]);
return 0;
}
标签:二分法
原文地址:http://12451545.blog.51cto.com/12441545/1921901