对有序的数组使用二分查找,可提高效率
二分查找,下标由0开始,递归结束条件,data[p] == key || start >= end
int BinaryS(int *data,int start,int end,int key)
{
int result;
int p = (start + end) / 2;
if (data[p] == key || start >= end) {
if (data[p] == key) {
result = p;
printf("\nyes! index is %d\n",p);
return result;
}
else
{
result = -1;
printf("\nno! %d\n",-1);
return result;
}
//return result;
}
else
{
if (data[p] > key) {
result = BinaryS(data, start, p, key);
}
else
{
result = BinaryS(data, p + 1, end, key);
}
return result;
}
}