应用题 32.给出折半查找的递归算法,并给出算法时间复杂度分析。
【正确答案】 int BinSrch(rectype r[],int k,low,high){
//在长为n的有序表中查找关键字k,若查找成功,返回k所在位置,查找失败返回O
if(low<=high){ //low和high分别是有序表的下界和上界
mid=(low+high)/2;
if(r[mid].key==k)return(mid);
else if(r[mid].key>k)retum(BinSrch(r,k,mid+l,high));
}
else retum(BinSrch(r,k,low,mid一1));
}
else retum 0: //查找失败
}
算法时间复杂度为0(log2n)。
【答案解析】