binary search .
#include <stdio.h>
int cmp_count = 0;
int bsearch(int array[],int start,int end,int p){
if(start > end)
return -1;
int mid = (start + end) / 2;
while(start != end){
if(array[mid] >= p)
end = mid;
else
start = mid + 1;
mid = (start + end) / 2;
cmp_count++;
}
if(array[start] == p)
return start;
return -1;
}
int main(int argc, const char *argv[])
{
int array[11] = {1,3,7,7,7,7,7,8,9,9,10};
int first_pos = bsearch(array,0,10,7);
printf("比较%d次,第一次出现位置:%d,值:%d\n",cmp_count,first_pos,array[first_pos]);
return 0;
}