一、前言
哈希查找的资料就看这里吧 http://blog.csdn.net/xiaoping8411/article/details/7706376 ,哈希查找的本质就是定好表长,创建哈希表,哈希表上的表格就像桶子一样,需要将数据点,先映射为key值(防止奇怪的取值),之后再使用哈希函数映射为哈希地址,各个数据点的地址应该尽可能无规律和尽可能地分散,避免2个以上数据对应对应同个桶。
值得注意,哈希函数为key值对表长取余时,这个表长就是mod值,这个值最好取为远离2的幂次方的质数。
哈希函数设计一般可采用以下方法:
1.直接定址法。
2.除法取余法,这种方法用得多
3.数字分析法
4.平方取中法
5.折叠法
哈希函数解决两个不同数冲突的方法:
1.开放地址法,这种方法用得多,有线性探测法,随机探查法,双散列探查法等等等,本质都一样
2. 链接法(拉链法)。将具有同一散列地址的记录存储在一条线性链表中
二、代码
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
class HashFinder
{
public:
HashFinder(int *arr , int n ){
hashLen =19 ; //表长尽量取远离2的幂次方的质数,表长比数据长些
hashMap = new int [ hashLen ] ;
for(int i = 0 ; i < n ; ++i)
insertKey( arr[i] ); //插入key值数据到表,这里key实际就是数组元素啦
}
~HashFinder(){ delete [] hashMap; }
void insertKey( int e ){
//计算地址
int addr = e %hashLen;
while( hashMap[addr] != 0 ){ //如果桶里已经有数则使用线性探测法探测另一地址
addr = ( ++addr ) %hashLen;
}
hashMap[addr] = e;
}
void findD( int d ){
int addrD = d %hashLen ;
if ( hashMap[ addrD] == 0 ){
cout<<" No found!";
return ;
}
while( hashMap[ addrD] != 0 ){
if( hashMap[ addrD] == d ){
cout<<" founded!";
return ;
}else {
addrD = ( ++addrD ) %hashLen; //继续线性探测
}
}
cout<<" No found!";
}
private:
int hashLen ; //哈希表长度
int * hashMap ;
};
int main()
{
int arr[] = { 6 , 202 , 88, 102 , 100 , 41, 12 , 23 , 34 , 25 , 50, 41 , 11 };
int n = 13 ;
HashFinder hashFinder(arr , n );
hashFinder.findD( 34 );
}