#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次\n", k, i); else printf("失败:关键字%d,比较%d次\n", 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\n", 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\n", 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;
原文地址:https://www.cnblogs.com/KIROsola/p/11986689.html
时间: 2024-10-09 22:51:37