zoukankan      html  css  js  c++  java
  • 哈希表

     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("
    ");
    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 
    ", pos);
    57         else
    58                 printf("find error
    ");
    59         return 0;
    60 }
  • 相关阅读:
    让UIButton在按下时没有高亮效果
    如何让View一直沿z轴旋转
    App 应用通过网页打开 App Store
    Xcode/iOS: 如何判断代码运行在DEBUG还是RELEASE模式下?
    freemyapps 推荐链接
    [转]Git使用基础篇
    [转]anchorPoint 锚点解析
    Mac下如何看Swf文件
    Xcode 5: 将新项目同步到Svn上
    Shell 启动java程序
  • 原文地址:https://www.cnblogs.com/chris-cp/p/4175988.html
Copyright © 2011-2022 走看看