Week12 Hashing
Week12 Hashing
HASHING
HASHING HASHING
3 4
HASHING HASHING
• Hash function h(k) specifies the address where the pair (k, value) is stored • Collision: Two different keys have the same value of the hash function (hash code):
• h(k) should be simple and easy to compute • Resolution:
• Chaining: group keys having the same hash code into buckets
• Open Addressing
5 6
• Modulo: h(k) = k mod m where m is the size of the hash table • Modulo: h(k) = k mod m where m is the size of the hash table
7 8
HASHING: collision resolution by open addressing HASHING: collision resolution by open addressing
• Pairs (key, value) are stored in the table itself • get(k) and put(k, v) operations:
• Operations put(k, v) and get(k) need to probe the table until the desired slot found
• put(k, v): probe for finding a free slot for storing (k, v) get(k) put(k, v)
• get(k): probe for finding the slot where the key k is stored { {
• Probing order: h(k, 0), h(k, 1), h(k, 2), …, h(k, m-1) // T: the table // T: the table
i = 0; x.key = k; x.value = v;
• Methods
while(i < m) { i = 0;
• Linear probing: h(k, i) = (h1(k) + i) mod m where h1 is normal hash function
j = h(k,i); while(i < m) {
• Quadratic probing: h(k, i) = (h1(k) + c1i + c2i2) mod m where h1 is normal hash function if(T[j].key = k) { j = h(k,i);
• Double hashing: h(k, i) = (h1(k) + i * h2(k)) mod m where h1 and h2 are normal hash functions return T[j]; if(T[j] = NULL) {
} T[j] = x; return j;
i = i + 1; }
} i = i + 1;
return NULL; }
} error(“Hash table overflow”);
}
9 10
HASHING: collision resolution by open addressing HASHING: collision resolution by open addressing
• Exercise: A table has m slots, apply the open addressing method in which h(k, i) has the form: • Exercise: A table has m slots, apply the open addressing method in which h(k, i) has the form:
h(k, i) = (k mod m + i) mod m h(k, i) = (k mod m + i) mod m
• Initialization, the table is free, present the status of the table after inserting following sequence of • Initialization, the table is free, present the status of the table after inserting following sequence of
keys 7, 8, 6, 17, 4, 28 into the table with m = 10 keys 7, 8, 6, 17, 4, 28 into the table with m = 10
0 1 2 3 4 5 6 7 8 9
28 x x x 4 x 6 7 8 17
11 12
HASHING: hash functions
• Key k is an integer
• h(k) = mod m
• Key is a string
• k = s[0..n-1] h(k) = (s[0]*256n-1 + s[1]*256n-2 + … + s[n-1]*2560) mod m
THANK YOU !
13 14