问题描述:
1.在计算机科学中,hash table 是一种常用的数据结构,它本质上是一种关联容器,它映射一个key 到value。它通过一个hash function把key映射成一个整数值,这个整数值对应存放value值的容器的下标。
2.它主要支持三种操作:插入key,value对(insert),查询(search)给定key, 删除key, value对(delete);
3.它三种操作的平均时间复杂度为O(1),最糟糕情况下的时间复杂度为O(n);
4.hash table要处理核心问题是选择好的hash function,这能使得key映射出的index足够分散均匀,尽量减少碰撞(不同的key映射到同一个index),为了消除碰撞产生,一般常用几种方法:Separate chaining, Linear probing,Quadratic probing, Rehash, double Hashing,详细细节请参看维基百科;
5.本文给出利用Rehash的策略来消除碰撞;
6.本文设计测试用例,比较了hashtable 和STL map 的操作性能。发现执行相同的操作,hashtable 所消耗时间为STL map 九分之一;
程序代码:
#ifndef _HASH_TABLE_H_
#define _HASH_TABLE_H_
#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <assert.h>
#include <string>
#include "windows.h"
/*
* Compare function
*
*/
static bool StrCompare( const char* first, const char* second )
{
size_t firstLen = strlen(first);
size_t secondLen = strlen(second);
return firstLen == secondLen && !strcmp( first, second );
}
/*
* Hash function
*
*/
static unsigned int ImplHashFunc( const char* buf, int len )
{
unsigned int hash = 5381;
while(len--)
{
hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
}
return hash;
}
/*
* Hash function
*
*/