#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#define OVERFLOW -2
#define ERROR 1
#define OK 0
#define MAXSIZE 10
using namespace std;
typedef int Status;
typedef struct{
int key;
}Table;
typedef struct{
Table *R;
int length;
}SSTable;
Status InitTable(SSTable &ST){
ST.R=new Table[MAXSIZE];
if(!ST.R) exit(OVERFLOW);
ST.length=0;
return OK;
}
Status GetTable(SSTable ST,int i,int e){
ST.R[i].key=e;
return OK;
}
int Search_Seq(SSTable ST,int key){//无哨兵顺序查找
int i;
for(i=ST.length;i>=1;i--)
if(ST.R[i].key==key)
return i;
}
int Search(SSTable ST,int key){//有哨兵顺序查找
int i;
ST.R[0].key=key;
for(i=ST.length;ST.R[i].key!=key;i--);
return i;
}
int Search_Bin(SSTable ST,int key){//折半查找
int low=1,high=ST.length,mid;
while(low<=high){
mid=(low+high)/2;
if(key==ST.R[mid].key)return mid;
else if(key<ST.R[mid].key)high=mid-1;
else low=mid+1;
}
return 0;
}
int main(){
SSTable ST;
InitTable(ST);
int n,i,e;
printf("请输入元素个数:\n");
scanf("%d",&n);
ST.length=n;
printf("请输入%d个整形数:\n",n);
for(i=1;i<=n;i++){
scanf("%d",&e);
GetTable(ST,i,e);
}
int k;
printf("请输入查找的数字:\n");
scanf("%d",&k);
int c,j;
printf("1.无哨兵顺序查找2.有哨兵顺序查找3.折半查找\n");
while(scanf("%d",&c)!=EOF){
switch(c){
case(1):j=Search_Seq(ST,k);break;
case(2):j=Search(ST,k);break;
case(3):j=Search_Bin(ST,k);break;
}
printf("%d在第%d个位置\n",k,j);
}
return 0;
}