7.2.4
6.写出折半查找的递归算法。初始调用时,low为1,high为ST.length。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
} SSTable;
int mid;
int BinSearchRec(SSTable ST, ElemType key, int low, int high)
{
if (low > high) return 0;
mid = (low + high) / 2;
if (key > ST.elem[mid]) BinSearchRec(ST, key, mid + 1, high);
else if (key < ST.elem[mid]) BinSearchRec(ST, key, low, mid - 1);
else return mid;
}
int main()
{
int n;
scanf("%d", &n);
SSTable ST;
ST.length = n;
ST.elem = (ElemType *)malloc(sizeof(ElemType) * (n + 1));
for (int i = 1; i <= ST.length; i++) scanf("%d", &ST.elem[i]);
ElemType t;
scanf("%d", &t);
int ans = BinSearchRec(ST, t, 1, ST.length);
printf("%d\n", ans);
return 0;
}