1.从有序可重复数组中寻找一个元素首次出现的位置(由有序可知,可以使用二分查找来提高搜索速度,不过需要注意可重复性的特点,因此在这个基础上略微修改查找函数即可)
int find_num(int *data, int num, int low, int high){ int mid; mid = (low+high)/2; if(high>low){ if(*(data+mid)==num) return find_num(data, num, low, mid); else if(*(data+mid)>num) return find_num(data, num, low, mid-1); else return find_num(data, num, mid+1, high); } else{ if(*(data+high)==num) return low; else return -1; } } int main(int argc, char *argv[]){ int result, num=6; int testdata[]={1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6}; result = find_num(testdata, num, 0, sizeof(testdata)/sizeof(int)); result>=0?printf("find %d in testdata[%d] ", num, result):printf("not found "); system("pause"); return 0; }