Analysis of Algorithms

Download Report

Transcript Analysis of Algorithms

Hash Tables
0
1
2
3
4
7/20/2015 5:50 PM

025-612-0001


451-229-0004
Hash Tables
981-101-0004
1
Outline and Reading
Hash functions and hash tables (§8.3)
Hash function details


Hash code map (§8.3.3)
Compression map (§8.3.4)
Collision handling (§8.3.5)



Chaining
Linear probing
Double hashing
7/20/2015 5:50 PM
Hash Tables
2
Hashing:
A method for directly referencing items
in a dictionary by doing arithmetic
transformations on keys into dictionary
addresses.
A hush function is perfect if there is no
key collision, that is, two keys hash to
the same hash value.
7/20/2015 5:50 PM
Hash Tables
3
An Example:
suppose:
MagicNumber = 15
int h(String s) {
return ((s[0] + s[1])% MagicNumber);
}
suppose:
planet solarSystem[MagicNumber];
class planet {
String name;
int numMoons;
double sunDistance;
….
}
7/20/2015 5:50 PM
Hash Tables
4
Suppose:
solarSystem[h(“Mercury”)] = new planet(“Mercury”, 0, 36.0);
solarSystem[h(“Venus”)] = new planet(“Venus”, 0, 67.27);
solarSystem[h(“Earth”)] = new planet(“Earth”, 1, 93.0);
solarSystem[h(“Mars”)] = new planet(“Mars”, 2, 141.71);
solarSystem[h(“Jupiter”)] = new planet(“Jupiter”, 16, 483.88);
solarSystem[h(“Saturn”)] = new planet(“Saturn”, 12, 887.14);
solarSystem[h(“Uranus”)] = new planet(“Uranus”, 5, 1783.98);
solarSystem[h(“Neptune”)] = new planet(“Neptune”, 2, 2795);
solarSystem[h(“Pluto”)] = new planet(“Pluto”, 1, 3675);
Where are they located
7/20/2015 5:50 PM
Hash Tables
5
“Ju” in ASCII are 74 and 117, 74 + 117 = 191;
191 % 15 = 11;
h(“Mercury”) = 13
h(“Venus”) = 7
h(“Earth”) = 1
h(“Mars”) = 9
h(“Jupiter”) = 11
h(“Saturn”) = 0
h(“Uranus”) = 4
h(“Neptune”) = 14
h(“Pluto”) = 8
Thus, our search function is simply:
planet search(String s){ return solarSystem[h(s)]; }
7/20/2015 5:50 PM
Hash Tables
6
Hash Functions and Hash Tables
A hash function h maps
keys of a given type to
integers in a fixed interval
[0, N - 1]
Example:
h(x) = x mod N
is a hash function for
integer keys
The integer h(x) is called
the hash value of key x
The goal of a hash
function is to uniformly
disperse keys in the
range [0, N - 1]
7/20/2015 5:50 PM
A hash table for a given key
type consists of


Hash function h
Array (called table) of size N
When implementing a dictionary
with a hash table, the goal is to
store item (k, o) at index i = h(k)
A collision occurs when two
keys in the dictionary have
the same hash value
Collision handing schemes:
Hash Tables


Chaining: colliding items
are stored in a sequence
Open addressing: the
colliding item is placed in a
different cell of the table
7
Example
7/20/2015 5:50 PM
0
1
2
3
4

025-612-0001


451-229-0004
981-101-0004
…
We design a hash table
for a dictionary storing
items (SSN, Name),
where SSN (social
security number) is a
nine-digit positive
integer
Our hash table uses an
array of size N = 10,000
and the hash function
h(x) = last four digits of x
We use chaining to
handle collisions
9997
9998
9999

200-751-9998

Hash Tables
8
Hash Functions
A hash function is
usually specified as the
composition of two
functions:
Hash code map:
h1: keys  integers
Compression map:
h2: integers  [0, N - 1]
7/20/2015 5:50 PM
Hash Tables
The hash code map
is applied first, and
the compression map
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
9
Hash Code Maps
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)
7/20/2015 5:50 PM
Hash Tables
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)
10
Hash Code Maps (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
at most 6 collisions on a set
of 50,000 English words)
7/20/2015 5:50 PM
Hash Tables
Polynomial p(z) can be
evaluated in O(n) time
using Horner’s rule:

The following
polynomials are
successively computed,
each from the previous
one in O(1) time
p0(z) = an-1
pi (z) = an-i-1 + zpi-1(z)
(i = 1, 2, …, n -1)
We have p(z) = pn-1(z)
11
Compression Maps
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
7/20/2015 5:50 PM
Hash Tables
Multiply, Add and
Divide (MAD):



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
12
Linear Probing
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
7/20/2015 5:50 PM
Example:


h(x) = x mod 13
Insert keys 18, 41,
22, 44, 59, 32, 31,
73, in this order
0 1 2 3 4 5 6 7 8 9 10 11 12
41
18 44 59 32 22 31 73
0 1 2 3 4 5 6 7 8 9 10 11 12
Hash Tables
13
Search with Linear Probing
Consider a hash table A
that uses linear probing
findElement(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
7/20/2015 5:50 PM
Algorithm findElement(k)
i  h(k)
p0
repeat
c  A[i]
if c = 
return NO_SUCH_KEY
else if c.key () = k
return c.element()
else
i  (i + 1) mod N
pp+1
until p = N
return NO_SUCH_KEY
Hash Tables
14
Updates with Linear Probing
To handle insertions and
deletions, we introduce a
special object, called
AVAILABLE, which replaces
deleted elements
removeElement(k)



insert Item(k, o)



We search for an item with
key k
If such an item (k, o) is
found, we replace it with the
special item AVAILABLE and
we return element o
Else, we return
NO_SUCH_KEY
7/20/2015 5:50 PM
Hash Tables
We throw an exception if
the table is full
We start at cell h(k)
We probe consecutive
cells until one of the
following occurs
 A cell i is found that is
either empty or stores
AVAILABLE, or
 N cells have been
unsuccessfully probed

We store item (k, o) in
cell i
15
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
7/20/2015 5:50 PM
Hash Tables
Common choice of
compression map for the
secondary hash function:
d2(k) = q - k mod q
where


q<N
q is a prime
The possible values for
d2(k) are
1, 2, … , q
16
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 this order
7/20/2015 5:50 PM
k
18
41
22
44
59
32
31
73
h (k ) d (k ) Probes
5
2
9
5
7
6
5
8
3
1
6
5
4
3
4
4
5
2
9
5
7
6
5
8
10
9
0
0 1 2 3 4 5 6 7 8 9 10 11 12
31
41
18 32 59 73 22 44
0 1 2 3 4 5 6 7 8 9 10 11 12
Hash Tables
17
Performance:
Let N be the number of slots of a hash table,
n be the number of items in the table, we
define load factor as:
 = n/N
If the hash function randomly distributes
keys through the table, then the expected
length of a successful search path is:
lengthsucc = ½(1 + 1/(1- ))
7/20/2015 5:50 PM
Hash Tables
18
Performance:
The expected length of an unsuccessful
search is approximately:
lengthunsucc = ½( 1 + 1/(1 - )2)
7/20/2015 5:50 PM
Hash Tables
19
Problems with Probing:
The size of the hash table must be
fixed in advance.
The search costs increase dramatically
as the table becomes nearly full.
Need a special object, called
AVAILABLE, to implement “delete”
operation.
7/20/2015 5:50 PM
Hash Tables
20
Collision resolution using
Linked Lists:
Dynamically allocate space.
Easy to insert/delete an item
Need a link for each node in the hash
table.
7/20/2015 5:50 PM
Hash Tables
21
Performance:
Let N be the size of the hash table, n the
number of items in the table’s linked lists, if
all input sequences are equally likely and the
hash function randomly distributes keys over
the table, the expected length of a linked list
is n/N.
lengthsucc = ½(n/N)
lengthunsucc = n/N
7/20/2015 5:50 PM
Hash Tables
22
Conclusion:
In the worst case, searches,
insertions and removals on a
hash table take O(n) time
The worst case occurs when
all the keys inserted into the
dictionary collide
The load factor  = n/N
affects the performance of a
hash table
Assuming that the hash
values are like random
numbers, it can be shown
that the expected number of
probes for an insertion with
open addressing is
1 / (1 - )
7/20/2015 5:50 PM
Hash Tables
The expected running
time of all the dictionary
ADT operations in a
hash table is O(1)
In practice, hashing is
very fast provided the
load factor is not close
to 100%
Applications of hash
tables:



small databases
compilers
browser caches
23
3 a
Locators
1 g
7/20/2015 5:50 PM
Hash Tables
4 e
24
Outline and Reading
Locators (§8.7)
Locator-based methods
Implementation
Positions vs. Locators
7/20/2015 5:50 PM
Hash Tables
25
Locators
A locators identifies and tracks a
(key, element) item within a data
structure
A locator sticks with a specific
item, even if that element
changes its position in the data
structure
Intuitive notion:




key(): returns the key of the
item associated with the locator
element(): returns the element
of the item associated with the
locator
7/20/2015 5:50 PM
Hash Tables
Orders to purchase and
sell a given stock are
stored in two priority
queues (sell orders and
buy orders)
 the key of an order is
the price
 the element is the
number of shares
claim check
reservation number
Methods of the locator ADT:

Application example:


When an order is placed,
a locator to it is returned
Given a locator, an order
can be canceled or
modified
26
Locator-based Methods
Locator-based priority queue
methods:





insert(k, o): inserts the item
(k, o) and returns a locator
for it
min(): returns the locator of
an item with smallest key
remove(l): remove the item
with locator l
replaceKey(l, k): replaces
the key of the item with
locator l
replaceElement(l, o):
replaces with o the element
of the item with locator l
7/20/2015 5:50 PM
Hash Tables

locators(): returns an iterator
over the locators of the items
in the priority queue
Locator-based dictionary
methods:




insert(k, o): inserts the item
(k, o) and returns its locator
find(k): if the dictionary
contains an item with key k,
returns its locator, else return
the special locator
NO_SUCH_KEY
remove(l): removes the item
with locator l and returns its
element
locators(), replaceKey(l, k),
replaceElement(l, o)
27
Implementation
The locator is an
object storing



key
element
position (or rank) of
the item in the
underlying structure
6 d
3 a
9 b
In turn, the position
(or array cell) stores
the locator
Example:

binary search tree
with locators
7/20/2015 5:50 PM
1 g
Hash Tables
4 e
8 c
28
Positions vs. Locators
Position



Locator
represents a “place” in a
data structure
related to other positions in
the data structure (e.g.,
previous/next or
parent/child)
implemented as a node or
an array cell
Position-based ADTs (e.g.,
sequence and tree) are
fundamental data storage
schemes
7/20/2015 5:50 PM
Hash Tables



identifies and tracks a (key,
element) item
unrelated to other locators in
the data structure
implemented as an object
storing the item and its
position in the underlying
structure
Key-based ADTs (e.g., priority
queue and dictionary) can be
augmented with locator-based
methods
29