Lec5 - Hashing
Lec5 - Hashing
hash func.
h(element) …
length –1
elements (e.g., strings) hash table
Dr Amr ElMasry & Dr Mervat Mikhail 1
Hashing and hash functions
The idea: somehow we map every element into
some index in the array ("hash" it);
this is its one and only place that it should go
Lookup becomes constant-time : simply look at that one
slot again later to see if the element is there
add, remove, contains all become O(1) !
h(i) = i % array.length
Dr Amr ElMasry & Dr Mervat Mikhail
2
Hash function example
elements = Integers 0
h(i) = i % 10 1 41
add 41, 34, 7, and 18 2
constant-time lookup: 3
just look at i % 10 again later 4 34
5
Hash tables have no ordering information! 6
Expensive to do following:
7 7
another option:
perform a weighted sum of the letters, and hash on that
h(s) = % array.length
Dr Amr ElMasry & Dr Mervat Mikhail 12
Analysis of hash tables
main operation: lookup of item in table
What is worst-case cost of finding an item?
O(n)
Worst-case analysis doesn’t make sense for
hash tables, look at average case cost
Cost highly depend on the load factor
Load factor is a measure for “till what load”
Load factor of a hash table is the ratio:
N no. of elements inserted in HT
M array size
Dr Amr ElMasry & Dr Mervat Mikhail 13
Rehashing and hash table size
rehash: increasing the size of a hash table's array,
and re-storing all of the items into the array using the
hash function
can we just copy the old contents to the larger array?