开放定址法构造哈希表
Posted kirosola
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了开放定址法构造哈希表相关的知识,希望对你有一定的参考价值。
#define NULLKEY -1 #define DELKEY -2 typedef int KeyType; typedef struct { KeyType key; int count;//探测次数域 }HashTable;
void InsertHT(HashTable HT[], KeyType k, int& n, int m, int p) { //n哈希表中总元素的个数,m表长 int i, adr; adr = k % p; if (HT[adr].key == NULLKEY || HT[adr].key == DELKEY) { HT[adr].key = k; HT[adr].count = 1; } else { i = 1; do { adr = (adr + 1) % m;//是m不是p i++; } while (HT[adr].key != NULLKEY && HT[adr].key != DELKEY); HT[adr].key = k; HT[adr].count = i; } n++; }
void CreateHT(HashTable HT[], KeyType keys[], int& n, int m, int p,int n1) { //n1为keys数组长度 int i; for ( i = 0; i < m; i++) { HT[i].key = NULLKEY; HT[i].count = 0; } n = 0; for (i = 0; i < n1; i++) InsertHT(HT, keys[i], n, m, p); }
bool DeletHT(HashTable HT[], KeyType k, int& n, int m, int p) { int adr = k % p; while (HT[adr].key != NULLKEY && HT[adr].key != k) adr = (adr + 1) % m; if (HT[adr].key == k) { HT[adr].key = DELKEY; return true; } else return false; }
void SerachHT(HashTable HT[], KeyType k, int& n, int m, int p) { int i = 1; int adr = k % p; while (HT[adr].key != NULLKEY && HT[adr].key != k) { adr = (adr + 1) % m; i++; } if (HT[adr].key == k) printf("成功:关键字%d,比较%d次 ", k, i); else printf("失败:关键字%d,比较%d次 ", k, i); }
void ASL(HashTable HT[], int n, int m, int p) { int i, j, s; int suc = 0,unsuc = 0; for (i = 0; i < m; i++) { if (HT[i].key != NULLKEY) suc += HT[i].count; } printf("成功情况下ASL=%g ", suc * 1.0 / n); for (i = 0; i < p; i++) { s = 1; j = i; while (HT[j].key != NULLKEY) { s++; j = (j + 1) % m; } unsuc += s; } printf("失败情况下ASL=%g ", unsuc * 1.0 / p); }
测试用例:KeyType keys[] = { 16,74,60,43,54,90,46,31,29,88,77 },int p = 13, m = 13, n = 0, n1 = 11;
以上是关于开放定址法构造哈希表的主要内容,如果未能解决你的问题,请参考以下文章