- 顺序查找
int SeqSearch(int a[],int k,int len){
int i = len;
while(a[i]!=k)
i--;
return i;
}
- 折半查找(非递归)
int BinSearch(int a[],int k,int len){
int mid,low=0,high=len-1;
while(low<high){
count++;
mid = (low+high)/2;
if(k<a[mid])
high = mid-1;
else if(k>a[mid])
low = mid+1;
else
return mid;
}
return -1;
}
- 折半查找(递归)
int BinSearch(int k,int low,int high){
if(low>high) return -1;
else{
int mid = (low+high)/2;
if(k<a[mid]) return BinSearch(k,low,high)
else if(k>a[mid]) return BinSearch(k,mid+1,high);
else return mid;
}
}
- 散列查找
void insert(int *ht,int *s,int len){
int pos,i,count;
for(i = 0;i<len;i++){
count = 1;
pos = s[i]%Max;
while(ht[pos]!=0){
pos = (s[i]+count)%Max;
count++;
}
ht[pos] = s[i];
cout<<"元素 "<<s[i]<<" 插入位置为下标 "<<pos<<endl;
}
}
int search(int *ht,int k){
int i;
count=0;
int j = k%Max;
i=j;
while(ht[i]!=0){
count++;
if(ht[i]==k) return i;
else i=(i+1)%Max;
}
return -1;
}