9.26② 试将折半查找算法改写成递归算法。
实现下列函数:
int BinSearch(SSTable s, int low, int high, KeyType k);
/* Index the element which key is k */
/* in StaticSearchTable s. */
/* Return 0 if x is not found. */
静态查找表的类型SSTable定义如下:
typedef struct {
KeyType key;
... ... // 其他数据域
} ElemType;
typedef struct {
ElemType *elem;
int length;
/* Index the element which key is k */
/* in StaticSearchTable s. */
/* Return 0 if x is not found. */
{
if(low>high)return 0;
int m=(low+high)/2;
if(s.elem[m].key==k)return m;
if(k<s.elem[m].key)
return BinSearch(s,low,m-1,k);
if(k>s.elem[m].key)
return BinSearch(s,m+1,high,k);
}
实现下列函数:
int BinSearch(SSTable s, int low, int high, KeyType k);
/* Index the element which key is k */
/* in StaticSearchTable s. */
/* Return 0 if x is not found. */
静态查找表的类型SSTable定义如下:
typedef struct {
KeyType key;
... ... // 其他数据域
} ElemType;
typedef struct {
ElemType *elem;
int length;
} SSTable;
/* Index the element which key is k */
/* in StaticSearchTable s. */
/* Return 0 if x is not found. */
{
if(low>high)return 0;
int m=(low+high)/2;
if(s.elem[m].key==k)return m;
if(k<s.elem[m].key)
return BinSearch(s,low,m-1,k);
if(k>s.elem[m].key)
return BinSearch(s,m+1,high,k);
}