Upload
jordan-brooks
View
230
Download
1
Tags:
Embed Size (px)
Citation preview
1
Maps,Hash Tables,Skip Lists,
Sets
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
2
Maps & Dictionaries
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
Maps
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets3
• A map models a searchable collection of key-value entries• The main operations of a map are for searching, inserting, and
deleting entries• Multiple entries with the same key are not allowed• Applications:
address book student-record database
Ordered maps (dictionaries) allow nearest neighbor queries in addition to the above three (see also Slide 11).
The Map ADT
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets4
get(k): if the map M has an entry with key k, return its associated value; else, return null
put(k, v): insert entry (k, v) into the map M; if key k is not already in M, then return null;
else, return old value associated with k
remove(k): if the map M has an entry with key k, remove it from M and return its associated value; else, return null
entrySet(): return an iterable collection of the entries in M
keySet(): return an iterable collection of the keys in M
values(): return an iterator of the values in M
size()
isEmpty()
ExampleOperation Output Map
isEmpty() true Øput(5,A) null (5,A)put(7,B) null (5,A),(7,B)put(2,C) null (5,A),(7,B),(2,C)put(8,D) null (5,A),(7,B),(2,C),(8,D)put(2,E) C (5,A),(7,B),(2,E),(8,D)get(7) B (5,A),(7,B),(2,E),(8,D)get(4) null (5,A),(7,B),(2,E),(8,D)get(2) E (5,A),(7,B),(2,E),(8,D)size() 4 (5,A),(7,B),(2,E),(8,D)remove(5) A (7,B),(2,E),(8,D)remove(2) E (7,B),(8,D)get(2) null (7,B),(8,D)isEmpty() false (7,B),(8,D)
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets5
The Java Map Hierarchy
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets6
«interface»Map
(§ 10.1.1)
«interface»SortedMap
(§ 10.3)
AbstractMap(§ 10.1.3)
AbstractSortedMap(§ 10.3)
UnsortedTableMap(§ 10.1.4)
AbstractHashMap(§ 10.2.4)
SortedTableMap(§ 10.3.1)
TreeMap(chapter 11)
ChainHashMap(§10.2.4)
ProbeHashMap(§ 10.2.4)
(additionalsubclasses)
A Simple List-Based Map• We can implement a map using an unsorted list – We store the items of the map in a list S
(based on a doubly linked list), in arbitrary order
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets7
trailerheader nodes/positions
entries
9 c 6 c 5 c 8 c
The get(k) AlgorithmAlgorithm get(k)
B M.positions() // B is an iterator of the positions in Swhile B.hasNext() do
p B.next() // the next position in B if p.element().getKey() = k then
return p.element().getValue()return null // there is no entry with key equal to k
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets8
The put(k,v) AlgorithmAlgorithm put(k,v)B M.positions()While B.hasNext() do
p B.next()if p.element().getKey() = k then
t p.element().getValue()M.set(p,(k,v))return t // return the old value
M.addLast((k,v))n n + 1 // increment variable storing number of entriesreturn null // there was no entry with key equal to k
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets9
The remove(k) AlgorithmAlgorithm remove(k)B M.positions()While B.hasNext() do
p B.next()if p.element().getKey() = k then
t p.element().getValue()M.remove(p)n n – 1 // decrement number of entriesreturn t // return the removed value
return null // there is no entry with key equal to k
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets10
Performance of a List-Based Map• Performance:
– put, get and remove take O(n) time since in the worst case we
traverse the entire sequence to look for an item with the given key
• The unsorted list implementation is effective only for maps of small size or for maps in which puts are the most common operations, while searches and removals are rarely performed (e.g., historical record of logins to a workstation)
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets11
12
Hash Tables
0
1
2
3
4 451-229-0004
981-101-0002
025-612-0001
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
Recall the Map ADT
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets13
get(k): if the map M has an entry with key k, return its associated value; else, return null
put(k, v): insert entry (k, v) into the map M; if key k is not already in M, then return null; else, return old value associated with k
remove(k): if the map M has an entry with key k, remove it from M and return its associated value; else, return null
entrySet(): return an iterable collection of the entries in M
keySet(): return an iterable collection of the keys in M
values(): return an iterator of the values in M
size()
isEmpty()
Intuitive Notion of a Map
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets14
• Intuitively, a map M supports the abstraction of using keys as indices with a syntax such as M[k].
• As a mental warm-up, consider a restricted setting in which a map with n items uses keys that are known to be integers in a range from 0 to N − 1, for some N ≥ n.
More General Kinds of Keys• But what should we do if our keys are not integers in
the range from 0 to N – 1?– Use a hash function to map general keys to corresponding
indices in a table.– For instance, the last four digits of a Social Security number.
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets15
01234 451-229-0004
981-101-0002
025-612-0001
…
Hash Functions &Hash Tables• A hash function h maps keys of a given type to
integers in a fixed interval [0, N - 1]• Example: h(k) = k mod N
is a hash function for integer keys• The integer h(k) is called the hash value of key k
• A hash table for a given key type consists of– Hash function h– Array (called table) of size N
• When implementing a map with a hash table, the goal is to store item (k, v) at index i = h(k)
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets16
Example• We design a hash table for a map
storing entries as (key, value) (SIN, Name), where SIN (social insurance number) is a ten-digit positive integer
• Our hash table uses an array of size N = 10,000 and the hash functionh(k) = last four digits of k
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets17
01234
999799989999
…451-229-0004
981-101-0002
200-751-9998
025-612-0001
Hash Functions• A hash function is usually
composed of two functions:
Hash code: h1: keys integers
Compression function: h2: integers [0, N - 1]
• The hash code is applied first, and the compression function is applied next on the result, i.e.,
h(x) = h2(h1(x))
• The goal of the hash function is to “disperse” the keys in an apparently random way
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets18
Hash Codes• Memory address:
We reinterpret the memory address of the key object as an integer (default hash code of all Java objects)
Good in general, except for numeric and string keys
• Integer cast: We reinterpret the bits of the key
as an integer Suitable for keys of length less
than or equal to the number of bits of the integer type (e.g., byte, short, int and float in Java)
• Component sum: We partition the bits of the key
into components of fixed length (e.g., 16 or 32 bits) and we sum the components (ignoring overflows)
Suitable for numeric keys of fixed length greater than or equal to the number of bits of the integer type (e.g., long and double in Java)
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets19
Hash Codes (cont.)• Polynomial accumulation:
We partition the bits of the key into a sequence of components of fixed length (e.g., 8, 16 or 32 bits) a0 a1 … an-1
We evaluate the polynomial
p(z) = a0 + a1 z + a2 z2 + … + an-1zn-
1
at a fixed value z, ignoring overflows
Especially suitable for strings (e.g., the choice z = 33 gives < 6 collisions on a set of 50,000 English words)
/** * Polynomial p(z) can be * evaluated in O(n) time by * Horner’s rule: **/
p 0;for (int i = n-1; i >= 0 ; i--)
p ai + z∗p;
return p;
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets20
Compression Functions• Division:
h2 (y) = y mod N The size N of the hash
table is usually chosen to be a prime
The reason has to do with number theory and is beyond the scope of this course
• MAD: Multiply, Add & Divide:
h2 (y) = (ay + b) mod N a and b are nonnegative
integers such that
a mod N 0
Otherwise, every integer would map to the same value b
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets21
22
Abstract Hash Map in Java
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
23
Abstract Hash Map in Java, 2
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
Collision Handling• Collisions occur when
different elements aremapped to the same cell
• Separate Chaining: – let each cell in the table point to a linked list of entries
that map there– Separate chaining is simple, but requires additional
memory outside the table
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets24
01234 451-229-0004 981-101-0004
025-612-0001
Map with Separate ChainingDelegate operations to a list-based map at each cell:Algorithm get(k)
return A[h(k)].get(k)
Algorithm put(k,v)t A[h(k)].put(k,v) if t = null then // k is a new key
n n + 1return t
Algorithm remove(k)t A[h(k)].remove(k)if t ≠ null then // k was found
n n - 1return t
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets25
26
Hash Table with Chaining
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
27
Hash Table with Chaining, 2
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
Open Addressing: Linear Probing• Open addressing: the colliding
item is placed in a different cell of the table
• Linear probing: handles collisions by placing the colliding item in the next (circularly) available table cell
• Each table cell inspected is referred to as a “probe”
• Colliding items lump together, causing future collisions to cause a longer sequence of probes
• Example:– h(x) = x mod 13– Insert keys 18, 41, 22, 44,
59, 32, 31, 73, in that order
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets28
0 1 2 3 4 5 6 7 8 9 10 11 12
7331223259441841
Search with Linear Probing• Consider a hash table A that
uses linear probing• get(k)
– We start at cell h(k) – We probe consecutive locations
until one of the following occurs• An item with key k is found, or• An empty cell is found, or• N cells have been unsuccessfully
probed
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets29
Algorithm get(k)i h(k)p 0repeat
c A[i]if c = return
nullelse if c.getKey()
= k return
c.getValue()else
i (i + 1) mod N
p p + 1until p = N
return null
Updates with Linear Probing• To handle insertions and
deletions, we introduce a special object, called DEFUNCT, which replaces deleted elements
• remove(k) search for an entry with key k If such an entry (k, v) is found,
replace it with the special item DEFUNCT and return element v
Else, return null
• put(k, v) throw an exception if the
table is full start at cell h(k) probe consecutive cells
until one of the following occurs A cell i is found that is either
empty or stores DEFUNCT, or N cells have been
unsuccessfully probed store (k, v) in cell i
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets30
31
Probe Hash Map in Java
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
32
Probe Hash Map in Java, 2
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
33
Probe Hash Map in Java, 3
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
Open Addressing:Double Hashing• Double hashing uses a
secondary hash function d(k) and handles collisions by placing an item in the first available cell of the series
(i + jd(k)) mod N for j = 0, 1, … , N – 1
• The secondary hash function d(k) cannot have zero values
• The table size N must be a prime to allow probing of all the cells
• Common choice of secondary hash function:
d(k) = q - k mod q
where– q < N– q is a prime
• possible values for d(k) are {1, 2, … , q}
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets34
Example of Double Hashing• Consider a hash table
storing integer keys that handles collision with double hashing– N = 13 – h(k) = k mod 13 – d(k) = 7 - k mod 7
• Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in that order
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets35
k h (k ) d (k ) Probes18 5 3 541 2 1 222 9 6 944 5 5 5 1059 7 4 732 6 3 631 5 4 5 9 073 8 4 8
0 1 2 3 4 5 6 7 8 9 10 11 12
31 41 183259732244
Performance of Hashing• O(n) worst case running time for
search, insert, and remove
e.g., when all inserted keys collide
• The load factor affects the performance
• With open addressing, assuming the hash values are random:
expected number of probes
• O(1) expected running time of all the dictionary operations
• In practice, hashing is very fast provided the load factor is not close to 100%
• Applications of hash tables:– small databases– compilers– browser caches
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets36
Summary
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets37
• Hash tables• Hash function =
hash code + compression function
• Hash codes:– Java default
memory address– Key integer cast– Component sum– Polynomial accumulation– . . .
• Collision handling:– Separate chaining– Open addressing:• Linear probing• Double hashing
• Performance of hashing– Worst-case– Expected case
38
Skip Lists+-
S0
S1
S2
S3
+- 10 362315
+- 15
+- 2315
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
What is a Skip List• A skip list for a set S of distinct (key, value) items is a series
of lists S0, S1 , … , Sh such that– Each list Si contains the special keys - and + – List S0 contains the keys of S in non-decreasing order – Each list is a subsequence of the previous one, i.e.,
S0 S1 … Sh
– List Sh contains only the two special keys• We show how to use a skip list to implement the map ADT
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets39
56 64 78 +31 34 44- 12 23 26
+-
+31-
64 +31 34- 23
S0
S1
S2
S3
Search• We search for a key x in a skip list as follows:
– We start at the first position of the top list – At the current position p, we compare x with y key(next(p))
x = y: we return element(next(p))x > y: we “scan forward” x < y: we “drop down”
– If we try to drop down past the bottom list, we return nullExample: search for 78
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets40
+-
S0
S1
S2
S3
+31-
64 +31 34- 23
56 64 78 +31 34 44- 12 23 26
scan forward
drop down
Randomized Algorithms• A randomized algorithm performs
coin tosses (i.e., uses random bits) to control its execution
• It contains statements of the typeb random() // b {0, 1}if b = 0
do A …else // b = 1
do B …
• Its running time depends on the outcomes of the coin tosses
• We analyze the expected running time of a randomized algorithm under the following assumptions– coins are unbiased, and – coin tosses are independent
• The worst-case running time of a randomized algorithm is often large but has very low probability (e.g., it occurs when all the coin tosses give “heads”)
• We use a randomized algorithm to insert items into a skip list
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets41
Insertion• To insert an entry (k, v) into a skip list, we use a randomized
algorithm:– We repeatedly toss a coin until we get tails, and we denote with i the
number of times the coin came up heads– If i h, we add to the skip list new lists Sh+1, … , Si +1, each containing
only the two special keys– We search for k in the skip list and find the positions p0, p1 , …, pi of
the items with largest key less than k in each list S0, S1, … , Si
– For j 0 .. i, we insert item (k, v) into list Sj after position pj
Example: insert key 15, with i = 2
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets42
+- 10 36
+-
23
23 +-
S0
S1
S2
+-
S0
S1
S2
S3
+- 10 362315
+- 15
+- 2315p0
p1
p2
Deletion• To remove an entry with key k from a skip list, we do:
– We search for k in the skip list and find the positions p0, p1 , …, pi
of the items with key k, where position pj is in list Sj
– We remove positions p0, p1 , …, pi from the lists S0, S1, … , Si
– We remove all but one list containing only the two special keys
Example: remove key 34
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets43
- +4512
- +
23
23- +
S0
S1
S2
- +
S0
S1
S2
S3
- +4512 23 34
- +34
- +23 34p0
p1
p2
Implementation• We can implement a skip list with quad-nodes
• A quad-node stores:– entry– link to the node prev– link to the node next– link to the node below– link to the node above
• We also define special keys PLUS_INF and MINUS_INF, and we modify the key comparator to handle them
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets44
x
quad-node
Space Usage• The space used by a skip list
depends on the random bits used by each invocation of the insertion algorithm
• We use the following two basic probabilistic facts:
Fact 1: The probability of getting i consecutive heads when flipping a coin is 1/2i
Fact 2: If each of n entries is present in a set with probability p, the expected size of the set is np
• Consider a skip list with n entries– By Fact 1, we insert an entry
in list Si with probability 1/2i
– By Fact 2, the expected size of list Si is n/2i
• The expected number of nodes used by the skip list is
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets45
the expected space usage of a skip list with n items is O(n)
Height• The running time of the search an
insertion algorithms is affected by the height h of the skip list
• We show that with high probability, a skip list with n items has height O(log n)
• We use the following additional probabilistic fact:
Fact 3: If each of n events hasprobability p, the probability that at least one of those n events occurs is at most np
• Consider a skip list with n enteries– By Fact 1, we insert an entry in list Si
with probability 1/2i
– By Fact 3, the probability that list Si has at least one item is at most n/2i
• By picking i = 3log n, we have that the probability that S3log n has at least one entry is at most
n/23log n = n/n3 = 1/n2
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets46
the height of a skip list with n entries is at most 3log n with probability at least 1 - 1/n2
Search and Update Times• The search time in a skip list is
proportional to– number of drop-down steps, plus– number of scan-forward steps
• drop-down steps are bounded by the height of the skip list and thus are O(log n) with high probability
• To analyze the scan-forward steps, we use yet another probabilistic fact:
Fact 4: The expected number of coin tosses required in order to get tails is 2
• When we scan forward in a list, the destination key does not belong to a higher list– A scan-forward step is associated
with a former coin toss that gave tails
• By Fact 4, in each list the expected number of scan-forward steps is 2
• Thus, the expected number of scan-forward steps is O(log n)
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets47
in a skip list, the expected time fora search, insert, or delete is O(log n).
Summary• A skip list is a data structure for maps• It uses a randomized insertion algorithm
• In a skip list with n entries: – expected space is O(n)– expected time for search, insert and delete is O(log n)
• Using a more complex probabilistic analysis, one can show that these performance bounds hold with high probability
• Skip lists are fast and simple to implement in practice
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets48
49
Sets, Multisets, & Multimaps
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets
Definitions• A set is an unordered collection of elements, without duplicates,
that typically supports efficient membership tests. – Elements of a set are like keys of a map, but without any auxiliary values.
• A multiset (aka, bag) is a set-like container that allows duplicates.
• A multimap is similar to a traditional map, in that it associates values with keys; however, in a multimap the same key can be mapped to multiple values.– For example, the index of a book maps a given term to one or more
locations at which the term occurs.
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets50
Set ADT
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets51
Storing a Set in a List• We can implement a set with a list• Elements are stored sorted according to some canonical
ordering• The space used is O(n)
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets52
List
Nodes storing set elements in order
Set elements
Generic Merging• Generalized merge of
two sorted lists A and B• Template method
genericMerge• Auxiliary methods
– aIsLess– bIsLess– bothAreEqual
• Runs in O(nA + nB) time provided the auxiliary methods run in O(1) time
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets53
Algorithm genericMerge(A, B)S empty sequence
while A.isEmpty() B.isEmpty()a A.first().element(); b
B.first().element()if a < b
aIsLess(a, S); A.remove(A.first())
else if b < abIsLess(b, S); B.remove(B.first())
else // b = a bothAreEqual(a, b, S)A.remove(A.first());
B.remove(B.first())while A.isEmpty()
aIsLess(a, S); A.remove(A.first())while B.isEmpty()
bIsLess(b, S); B.remove(B.first())return S
Using Generic Merge for Set Operations• Any of the set operations can be implemented
using a generic merge• For example:
intersection: only copy elements that are duplicated in both lists
union: copy every element from both lists except for the duplicates
• All methods run in linear time
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets54
Multimap• A multimap is similar to a map, except that it
can store multiple entries with the same key• We can implement a multimap M by means of
a map M’– For every key k in M, let E(k) be the list of entries
of M with key k– The entries of M’ are the pairs (k, E(k))
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets55
Mulitmaps
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets56
Java Implementation
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets57
Java Implementation, 2
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets58
Java Implementation, 3
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets59
Summary• Sets, multisets, and multimaps• Implementation– linked list– hash table– skip list
• Generic merge• Set operations using generic merge
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets60
last Update: Nov 4, 2014EECS2011: Maps, Hash Tables, Skip Lists,
Sets61