COT 5410-01 Fall 2004
Algorithms
Chris Lacher
Notes 7: Set < Hash >
Hashing
Review:
Hash Functions
Review:
Hash Tables
Set < Hash >
Hash Structure
T
= type of elements in Set
s
= number of elements in set = size of Set
h
= hash function for
T
B
= Vector of Lists
b
= number of buckets = size of Vector
Hash Search Algorithm
t
= search value
Calculate
hash_value = h(t.key)
Calculate
index = hash_value % b
Search
B[index]
for
t
Returns
[index, List::Iterator]
Set::Includes(t):
[i,I]
= Hash Search
if (I.Valid() && t == *I) t = *I
(alternate)
return SetIterator(i,I)
Set::Insert(t):
[i,I]
= Hash Search
if (!I.Valid() || t != *I) B[i].Insert(I,t)
else *I = t;
Set::Remove(t):
[i,I]
= Hash Search
B[i].Remove(I)
Expected Runtime = O(average search time for List)
= O(average size of B[index]) = O(size of set / number of buckets)
= O(s/b)
Expected Runspace = O(s + b)
When O(s) = O(b): Runtime = O(1) and Runspace = O(s)
Set::Iterator < Hash >
Data
Interface: Bidirectional Iterator
Set::Begin()
Iterator::++()
Amortized runtime O(b/(s+1))