例27:哈希查找

哈希查找本身听着很是高端,然后呢,听着感觉很难的样子,但是其原理也是非常简单,其实他的意思就是说通过一个函数,直接把值的地址与值本身之间关联起来,成为一个地址 = F(值)的函数,所以这种方式的查找速度为O(1),是一种很快的查找方式。

1.在查找之前首先先建立哈希表,其实就是按照 地址=F(值) 函数给出值所应存储的地址。常用的哈希函数有五种:直接定址法,除数取余法,数字分析法,平方取中法,折叠法。具体方法此处不详细介绍了,读者可以上网搜索一下,很多介绍很详细的。

2.如果此地址已经保存了某个值,那么可以用解决冲突的方法解决,常用方法有开放地址法和链地址法。同样,此处不详细介绍,文末结束处会放个链接,大家可以看一下这篇介绍哈希查找的文章,大多方法都有介绍。

3.我们采用的是除数取余法(题目中给定H(key) = key%11),和开放地址法(“采用线性探测再散列”)的方法。

代码如下:

 1 #include<stdio.h> 
 2 #include<time.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 
 6 void InsertHash(int hash[],int nCount,int Value)
 7 {
 8      int hashAddress = Value%nCount;
 9      while(hash[hashAddress] != 0)
10      {
11                              hashAddress = (++hashAddress)%nCount;
12      }
13      hash[hashAddress] = Value;
14 }
15 
16 int SearchHash(int hash[],int nCount,int Value)
17 {
18      int hashAddress = Value%nCount;
19      while(hash[hashAddress] != Value && hash[hashAddress] != 0)
20      {
21                              hashAddress = (++hashAddress)%nCount;
22      }
23      if(hash[hashAddress] == 0)
24      {
25                           return -1;
26      }
27      else 
28      {
29           return hashAddress;
30      }
31 }
32 
33 int main()
34 {
35     int hash[11],nCount,Value,Address;
36     while(~scanf("%d",&nCount) && nCount)
37     {
38                                memset(hash,0,sizeof(hash));
39                                srand((unsigned long)time(0));
40                                printf("nCount: %d\n",nCount);
41                                for(int i = 0;i<nCount;i++)
42                                {
43                                        printf("123123123\n");
44                                        Value = rand()%50;
45                                        InsertHash(hash,11,Value);
46                                        printf("%d \n",Value);
47                                }
48                                scanf("%d",&Value);
49                                if(SearchHash(hash,11,Value) != -1)
50                                {
51                                                             printf("查找成功,查找值为:%d\n",SearchHash(hash,11,Value));
52                                }
53                                else
54                                {
55                                                             printf("查找失败!\n");
56                                }
57     }
58     
59     return 0;
60 }

另外文章地址:http://blog.csdn.net/xiaoping8411/article/details/7706376

转载于:https://www.cnblogs.com/FWFC/p/6292570.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值