Tossaporn Saengja

Hash Table

Idea

(figure from https://en.wikipedia.org/wiki/Hash_table)

index = f(key, array_size)
hash = hashfunc(key) // คิดค่า hash จาก hash function ของ key
index = hash % array_size // mod ค่า hash ด้วย array_size เพื่อป้องกัน index error

Polynomial hashing

(s[0]An1+s[1]An2++s[n1]A0)modB(s[0]A^{n-1} + s[1]A^{n-2} + \cdots + s[n-1]A^0) \mod B

ตัวอย่าง

(65×34+76×33+76×32+69×31+89×30)%97=52(65 \times 3^4 + 76 \times 3^3 + 76 \times 3^2 + 69 \times 3^1 + 89 \times 3^0) \% 97 = 52

ตัวอย่างโปรแกรม

#include <bits/stdc++.h>

using namespace std;

const int A = 3;
const int B = 97;

string hash_table[B];

int hash_function(string s) {
  int sm = 0;
  for (auto x : s) {
    sm *= A;
    sm += int(x);
    sm %= B;
  }
  return sm;
}

int main() {
  string s = "ALLEY";
  printf("Hash value of %s is %d\n", s.c_str(), hash_function(s));
  hash_table[hash_function(s)] = s;
}

ได้ output แบบนี้

Hash value of ALLEY is 52

Collision

Separate Chaining

https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg/900px-Hash_table_5_0_1_1_1_1_1_LL.svg.png

(figure from https://en.wikipedia.org/wiki/Hash_table)

Open addressing

https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Hash_table_5_0_1_1_1_1_0_SP.svg/760px-Hash_table_5_0_1_1_1_1_0_SP.svg.png

(figure from https://en.wikipedia.org/wiki/Hash_table)

เปรียบเทียบ