#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef int KeyType;
typedef int InfoType;
typedef struct{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct{
ElemType *R;
int length;
}SSTable;
// 设置监视哨的顺序查找
int Search_Seq(SSTable ST,KeyType 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,KeyType key){
int low=1;
int high=ST.length;
while(low<=high){
int 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(){
int i,key;
SSTable t;
t.R=new ElemType[MAXSIZE];
cout << "请输入顺序表长度:";
cin >> t.length;
cout << "请输入您要查找的顺序表:";
for(i=1;i<=t.length;i++)
cin>>t.R[i].key;
cout<<"请输入您要查找的数据元素:";
cin>>key;
if(Search_Seq(t,key))
cout<<"该元素在顺序表中的位置为"<<Search_Seq(t,key)<<"个元素"<<endl;
else
cout<<"未找到"<<endl;
cout<<endl;
cout << "请输入顺序表长度:";
cin >> t.length;
cout << "请输入您要查找的顺序表:";
for(i=1;i<=t.length;i++)
cin>>t.R[i].key;
cout<<"请输入您要查找的数据元素:";
cin>>key;
if(Search_Bin(t,key))
cout<<"该元素在顺序表中的位置为"<<Search_Bin(t,key)<<"个元素"<<endl;
else
cout<<"未找到"<<endl;
}
这样是否可行:
int Search(SSTable ST,KeyType key, index){
if (index==1){
方法1的代码
}
if (index==2){
方法2的代码
}
}