1、顺序查找和二分查找
#include<iostream>
using namespace std;
template<class T>
class Find{
public:
int SeqSearch(T list[],int len,T key){
if(len>0){
for(int i=0;i<len;i++){
if(list[i]==key)
return i;
}
return -1;
}
return -1;
}
int BinarySearch(T list[],int len,T key){
int start=0;
int end=len;
int index=0;
while(start<=end){
index=(start+end)/2;
if(list[index]==key)
return index;
if(list[index]>key){
end=index-1;
}
if(list[index]<key){
start=index+1;
}
}
return -1;
}
};
2、哈希表查找步骤
1、构建哈希表,散列函数
2、解决冲突
3、根据键值查找
#include<iostream>
#define Max 11
#define N 8
using namespace std;
int hashtable[Max];
int func(int value){
return value%Max;
}
int Search(int key){
int pos,t;
pos=fun(key);//获得余数
t=pos;
while(hashtable[t]!=key && hashtable[t]!=-1){
t=(t+1)/Max;
if(pos==t) {//饶了一圈没有找到
return -1;
}
}
if(hashtable[t]==-1){
return NULL;
}else{
return t;
}
}
void creathash(int key){
int pos,t;
pos=func(key);
t=pos;
while(hashtable[t]!=key && hashtable[t]!=-1){
t=(t+1)%Max;
if(pos==t){
cout<<"hashtable is full"<<endl;
return;
}
}
hashtable[t]=key;
}
3、二叉树排序查找
左子树小于根节点,右子树大于根节点,中序遍历递增
如果小于根节点,查找左子树,大于根节点,查找右子树
BSTree SearchBST(BSTree T,KeyType key){
if((!T)||key==T->data.key())
return T;
else if(key<T->day.key)
return SearchBST(T->left,key);
else return SearchBST(T->right,key);
}