哈希表

简介: 1 #include 2 #define HASH_LEN 13  //哈希表长度 3 #define TABLE_LEN 8  //数据长度 4 int data[TABLE_LEN] = {69, 65, 90, 37, 92, 6, 20, 54}; 5 int has...
 1 #include <stdio.h>
 2 #define HASH_LEN 13  //哈希表长度
 3 #define TABLE_LEN 8  //数据长度
 4 int data[TABLE_LEN] = {69, 65, 90, 37, 92, 6, 20, 54};
 5 int hash[HASH_LEN] = {0};    //initialize data is  0  初始化一个数组
 6 
 7 //将数值插入hash表中
 8 void InsertHash(int hash[], int m, int data)  
 9 {
10         int i;
11         i = data%13;    //get  hash address
12         while(hash[i]){ // the address used;判断冲突
13                 i++;  //解决冲突
14                 i = i % m;       
15         }
16         hash[i] = data;
17 }
18 
19 void CreateHash(int hash[], int m, int data[], int n)
20 {       
21         int i;
22         for(i=0;i<n;i++) //place the data to hash map
23         {         
24               InsertHash(hash, n, data[i]);
25         }
26 }
27 
28 int HashSearch(int hash[], int n, int key)
29 {
30         int i;
31         i = key%13; //get the hash address;
32         while(hash[i] &&hash[i]!=key) //is conflict?
33         {
34                 i++;
35                 i=i% n; //resolve confict       
36         }
37         if(hash[i]==0)
38                 return  -1;     //not find the data
39         else
40                 return i;       //find ok
41 }
42 
43 int main()
44 {
45         int key, i, pos;
46         CreateHash(hash, HASH_LEN, data, TABLE_LEN);    
47         printf("hash values: ");
48         for(i=0;i<HASH_LEN;i++)
49                 printf("%d  ", hash[i]);
50         printf("\n");
51         printf("input the key data:");
52         scanf("%d", &key);
53 
54         pos = HashSearch(hash, HASH_LEN, key);
55         if(pos>=0)
56                 printf("find ok, pos is NO.%d \n", pos);
57         else
58                 printf("find error\n");
59         return 0;
60 }

 

相关文章
|
4月前
|
存储 算法 Java
【算法系列篇】哈希表
【算法系列篇】哈希表
|
3月前
|
存储
闭散列哈希表
闭散列哈希表
|
11月前
|
存储 算法 Serverless
|
4月前
|
存储 Serverless
哈希及哈希表的实现
哈希及哈希表的实现
43 0
|
存储 缓存 算法
趣味算法——探索哈希表的神秘世界
前言: 在编程世界中,数据存储和检索的效率常常是我们关注的重点。对于这个问题,哈希表提供了一个既高效又实用的解决方案。哈希表是一种通过哈希函数将键转化为数组索引,以实现快速查找的数据结构。在大多数情况下,哈希表能够在常数时间内完成查找,插入和删除操作,因此在许多应用场景中得到了广泛使用。
61 0
|
存储 算法 Java
哈希表(散列表)详解
什么是哈希表,以及如何使用哈希表
|
存储 算法 JavaScript
关于散列表(哈希表)我所知道的
关于散列表(哈希表)我所知道的
56 0
|
存储 Java Serverless
哈希表以及哈希冲突
哈希表以及哈希冲突
127 0
哈希表以及哈希冲突
|
存储 算法 C++
C++:哈希:闭散列哈希表
讲解了哈希的概念以及哈希函数,简单实现了闭散列哈希。闭散列哈希的重点之一是取模操作。
C++:哈希:闭散列哈希表
|
存储 数据库
第 9 章 哈希表
散列表(Hash table, 也叫哈希表) ,是根据关键码值(Key value)而直接进行访问的数据结构。
82 1