本帖最后由 ing 于 2020-2-27 23:21 编辑
#include<malloc.h>
#include<stdio.h>
#define KeyType int
typedef struct
{
KeyType key;
}ElemType;
typedef struct
{
int length;
ElemType *elem;
}SSTable;
void create(SSTable **t)
{
int length;
printf("长度\n");
(*t) = (SSTable*)malloc(sizeof(SSTable));
scanf("%d", &length);
(*t)->length = length;
printf("元素\n");
(*t)->elem = (ElemType*)malloc((length + 1)*sizeof(ElemType));
for (int i = 1; i <= (*t)->length; i++)
{
scanf("%d", &(*t)->elem[i].key);
}
}
int binSec(SSTable **t)
{
printf("请输入查找数据的关键字:\n");
scanf("%d", &(*t)->elem[0].key);
int high = (*t)->length;
int low = 1;
int middle;
while (low <= high)
{
middle = (high + low) / 2;
if ((*t)->elem[0].key == (*t)->elem[middle].key)
return middle;
else if ((*t)->elem[0].key < middle)
high = middle - 1;
else
low = middle + 1;
}
return 0;
}
int main(int argc, char* argv[])
{
SSTable *t;
create(&t);
int location = binSec(&t);
if (location == 0)
printf("查找表中无该元素");
else
printf("数据在查找表中的位置为:%d", location);
}
1 failed
|