• 查找五:散列表查找


     1 //散列表
     2 #include<iostream>
     3 using namespace std;
     4 #define NULLKEY -32768
     5 #define HASHSIZE 12 //定义散列表长度为12
     6 
     7 struct HashTable
     8 {
     9     int *elem;  //数据元素存储基址
    10     int count;  //当前数组元素个数
    11 };
    12 
    13 int m = 0; //散列表长度
    14 
    15 //初始化散列表
    16 bool InitHashTable(HashTable *H)
    17 {
    18     m = HASHSIZE;
    19     H->count = m;
    20     H->elem = new int[m];
    21     for(int i=0;i<m;i++)
    22         H->elem[i] = NULLKEY;
    23     return true;
    24 }
    25 
    26 //散列函数
    27 int Hash(int key)
    28 {
    29     return key % m;
    30 }
    31 
    32 //插入关键字进散列表
    33 void InsertHash(HashTable *H, int key)
    34 {
    35     int addr = Hash(key);
    36     while(H->elem[addr] != NULLKEY)
    37     {
    38         addr = (addr+1)%m;
    39     }
    40     H->elem[addr] = key;
    41 }
    42 
    43 //散列表查找关键字
    44 bool SearchHash(HashTable H, int key, int *addr)
    45 {
    46     *addr = Hash(key);
    47     while(H.elem[*addr] != key)
    48     {
    49         *addr = (*addr+1)%m;
    50         if(H.elem[*addr]==NULLKEY || *addr == Hash(key))
    51             return false;
    52     }
    53     return true;
    54 }
    55 
    56 int main()
    57 {
    58     int arr[HASHSIZE]={12,67,56,16,25,37,22,29,15,47,48,34};
    59     int i,p,key,result;
    60     HashTable H;
    61 
    62     key=39;
    63 
    64     InitHashTable(&H);
    65     for(i=0;i<m;i++)
    66          InsertHash(&H,arr[i]);
    67     
    68     result=SearchHash(H,key,&p);
    69     if (result)
    70         cout<<"查找 "<< key <<" 的地址为:"<<p<<endl;
    71     else
    72         cout<<"查找 "<< key <<" 失败。"<<endl;
    73 
    74     for(i=0;i<m;i++)
    75     {
    76         key=arr[i];
    77         SearchHash(H,key,&p);
    78         cout<<"查找 "<< key <<" 的地址为:"<<p<<endl;
    79     }
    80 
    81     return 0;
    82 }
  • 相关阅读:
    mysql同步之otter/canal环境搭建完整详细版
    Linux安装aria2
    mysql多源复制(多主一从)配置
    分布式调度框架TBSchedule使用方法
    hbase shell插入根据条件查询数据
    hive内部表&外部表介绍
    Canal( 增量数据订阅与消费 )的理解及应用
    tidb入门
    ES命令
    java8新特性
  • 原文地址:https://www.cnblogs.com/jx-yangbo/p/5958077.html
Copyright © 2020-2023  润新知