另外一个经典的Hash实现

HASH表适用于不需要对整个空间元素进行排序,而是只需要能快速找到某个元素的场合,是一种以空间换时间的方法,本质也是线性表,但由一个大的线性表拆分为了多个小线性表,由于只需要查找小表,因此搜索速度就会线性查整个大表提高很多,理想情况下,有多少个小线性表,搜索速度就提高了多少倍,通常把小线性表的表头综合为一个数组,大小就是HASH表的数量。
在许多文献中推荐的对字符串散列效果很好的ELFhash函数,可以用来处理英文字典单词。
 
//  elfhash.cpp A simple program to illustrate the use of ELFhash.
#include  < stdlib.h >
#include 
< iostream.h >
#include 
< iomanip.h >
 
long  hash_table_size;
char  key[ 100 ];
int  hash;
 
//  The ELFhash function itself, modified for Project 4 (3/31/2002).
int  ELFhash( char *  key,  long  M)
{
     unsigned 
long h = 0;
     
while(*key) 
    
{
         h 
= (h << 4+ *key++;
         unsigned 
long g = h & 0xF0000000L;
         
if (g) h ^= g >> 24;
         h 
&= ~g;
     }

     
return h % M;
}


//  A sample driver for ELFhash.
int  main()  {
    cout 
<< "Please enter the size of the hash table:";
    cin 
>> hash_table_size;
    cout 
<< "Please enter a key:";
    cin 
>> setw(100>> key;

    hash 
= ELFhash(key,hash_table_size);

    cout 
<< "The hash of "" << key << "" is " << hash << endl;
 
    
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值