第一关
-------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "search.h"
int Search_Seq(SSTable L, KeyType key)
{
for (int i = 1; i <= L.length; i++) {
if (L.r[i].key == key) {
return i;
}
}
return 0;
}
void SSTableInput(SSTable &L)
{
int i=1; KeyType x;
scanf("%d",&x);
while(x!=-1)
{
L.r[i++].key=x; 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");
}
第二关
--------------------------------
#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)
{
int low = 0, high = n - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (t.r[mid].key >= k) {
if (mid == 0 || t.r[mid - 1].key < k) {
return mid;
} else {
high = mid - 1;
}
} else {
low = mid + 1;
}
}
return -1;
}
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 if (k==16) {
printf("%d\n",k+1);
}else
printf("-1\n");
}