第1关:顺序查找
编程要求
在右侧编辑器中补充代码,完成Search_Seq
函数,以实现顺序查找。具体要求如下:
Search_Seq():在表中查找其关键字等于key的记录,若找到返回该记录在表中位置,否则返回0。
测试说明
可在右侧文件夹中查看step1/Main.cpp
文件,以便于你的操作。
平台会对你编写的代码进行测试。
输入说明: 第一行输入若干记录的关键字,以-1标志结束。 第二行输入待查找的关键字。 输出说明: 第一行输出静态查找表L中各记录的关键字。 第二行输出查找的结果,如果找到,则输出该记录在表中的位置,否则输出not find!
测试输入: 37 21 75 55 64 19 -1
55 //待查找的关键字为55
预期输出: 37 21 75 55 64 19
4 //末尾换行
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "search.h"
int Search_Seq(SSTable L, KeyType key)
{
int i;
for (i = 1; i <= L.length; i++) {
if (L.r[i].key == key) {
return i; // 找到关键字等于key的记录,返回其在表中的位置
}
}
return 0; // 没有找到关键字等于key的记录,返回0
}
void SSTableInput(SSTable &L)
{
int i = 1; KeyType x;
scanf("%d", &x);
while (x != -1) {
L.r[i].key = x;
i++;
scanf("%d", &x);
}
L.length = i - 1;
}
void SSTableOutput(SSTable L)
{
int i;
for (i = 1; i <= L.length; i++) {
printf("%d ", L.r[i].key);
}
printf("\n");
}
第2关:二分查找法
编程要求
请在右侧编辑器的命名空间内填写相关代码,实现采用二分查找算法实现查找有序数组里大于等于K的第一个数字。
本关静态查找表采用顺序表组织方式,并假设顺序表中数据元素类型的定义如下:
测试说明
平台会对你编写的代码进行测试:
测试输入: 第一行 1 个整数 n 表示有序数组的大小 第二行 n 个整数表示数组里的元素 第三行 1 个整数 K
实际输出: 你返回的值
#include <stdio.h>
#define MAXSIZE 100
typedef int KeyType; //根据需要设定数据类型
typedef struct
{
KeyType key; //关键字字段
}ElemType;
typedef struct
{
ElemType r[MAXSIZE];
int length; // 表的长度
} SSTable;
int BinSearch(SSTable t,int n,int k) //拆半查找算法
{
/********** Begin **********/
int low=0,high=n-1;
int mid;
while(low<=high){
mid=(low+high)/2;
if(k<t.r[mid].key)
high=mid-1;
else if(k>t.r[mid].key)
low=mid+1;
else
return mid;
}//while
if(low>high)
if(k>t.r[mid].key)
return mid+1;
else return mid;
/********** End **********/
}
int main()
{
int i,j;
int n,k;
SSTable t;
scanf("%d",&n);
for (i=0;i<n;i++)
scanf("%d",&t.r[i].key);
scanf("%d",&k);
j=BinSearch(t,n,k);
if (j>=0 && j<n)
printf("%d\n",t.r[j].key);
else
printf("-1\n");
}