hash table - staff.informatics.buu.ac.thjanya/88621159/lecture/8_hashtable.pdf ·...
TRANSCRIPT
Hash Table
88621159 Data Structures and Algorithms 2/2561
การจดเกบข+อมล• เกบใน List
• เกบใน BST
12117สบ, ฿15
32621นำ, ฿10
15252จาน, ฿20
89133ชอน, ฿5
98105แกว, ฿18
89133ชอน, ฿5
15252จาน, ฿20
98105แกว, ฿18
12117สบ, ฿15 32621
นำ, ฿10
Hashing§ Hashing เปนเทคนคอกแบบหนงทนำมาใชในการเกบขอมลทมจำนวนมาก ๆ และตองการการคนหาทรวดเรว
§ เชน การเกบคำศพทในพจนานกรม การเกบขอมลของลกคา หรอการเกบขอมลหนงสอตาง ๆ ทมอยในหองสมด
§ Key คอขอมลทใชในการคนหาขอมล§ ใชสตรในการคำนวณตำแหนง (index) เรยกวา Hash Function
Ideas• Map large integers to smaller integers• Map non-integer keys to integers
[CS1020 Lecture 13: Hashing]
HASHING
:
Hash Table
66752378
68744483
h 17
h
97468744483,
data
66752378,data
h is a hash function
Note: we must store the key values. Why?
[CS1020 Lecture 13: Hashing]
Hash Table: Operations
insert (key, data)a[h(key)] = data // h is a hash function and a[] is an array
delete (key)a[h(key)] = null
find (key)return a[h(key)]
However, this does notwork for all cases! (Why?)
[CS1020 Lecture 13: Hashing]
:
Hash Table: Collision
67774385 h68744483,
data
66752378,data
This is called a “collision”, when two keys have the same hash value.
A hash function does not guarantee that two different keys go into different slots! It is usually a many-to-one mapping and not one-to-one.
E.g. 67774385 hashes to the same location of 66752378.
[CS1020 Lecture 13: Hashing]
Two Important Issues• How to hash?• How to resolve collisions?• These are important issues that can affect the
efficiency of hashing
[CS1020 Lecture 13: Hashing]
Hash Functions
Criteria of Good Hash Functions• Fast to compute• Scatter keys evenly throughout the hash table• Less collisions• Need less slots (space)
[CS1020 Lecture 13: Hashing]
Example of Bad Hash Function• Select Digits – e.g. choose the 4th and 8th digits of a phone number• hash(67754378) = 58• hash(63497820) = 90
• What happen when you hash Singapore’s house phone numbers by selecting the first three digits?
[CS1020 Lecture 13: Hashing]
Perfect Hash Functions• Perfect hash function is a one-to-one mapping between keys and hash values.
So no collision occurs.• Possible if all keys are known.• Applications: compiler and interpreter search for reserved words; shell
interpreter searches for built-in commands.• GNU gperf is a freely available perfect hash function generator written in C++
that automatically constructs perfect functions (a C++ program) from a user supplied list of keywords.• Minimal perfect hash function: The table size is the same as the number of
keywords supplied.
[CS1020 Lecture 13: Hashing]
Uniform Hash Functions• Distributes keys evenly in the hash table• Example• If k integers are uniformly distributed among 0 and X-1, we can map the
values to a hash table of size m (m < X) using the hash function below
úûú
êëê=
Î
Xkmkhash
Xk
)(
),0[k is the key value[ ]: close interval( ): open intervalHence, 0 ≤ k < Xë û is the floor function
[CS1020 Lecture 13: Hashing]
Division method (mod operator)• Map into a hash table of m slots.• Use the modulo operator (% in Java) to map an integer to a value
between 0 and m-1.• n mod m = remainder of n divided by m, where n and m are positive
integers.
The most popular method.
mkkhash %)( =
[CS1020 Lecture 13: Hashing]
Multiplication method1. Multiply by a constant real number A between 0 and 12. Extract the fractional part3. Multiply by m, the hash table size
ë û( )ë û kAkAmkhash -=)(The reciprocal of the golden ratio
= (sqrt(5) - 1)/2 = 0.618033 seems to be a good choice for A (recommended by Knuth).
[CS1020 Lecture 13: Hashing]
Hashing of strings (1/4)• An example hash function for strings:
hash(s) { // s is a string
sum = 0for each character c in s {
sum += c // sum up the ASCII values of all characters
}return sum % m // m is the hash table size
}
[CS1020 Lecture 13: Hashing]
Hashing of strings: Examples (2/4)hash(“Tan Ah Teck”)
= (“T” + “a” + “n” + “ ” + “A” + “h” + “ ” + “T” + “e” + “c” + “k”) % 11 // hash table size is 11= (84 + 97 + 110 + 32 + 65 + 104 + 32 + 84 + 101 + 99 + 107) % 11= 825 % 11= 0
[CS1020 Lecture 13: Hashing]
Hashing of strings: Examples (3/4)• All 3 strings below have the same hash value! Why?• Lee Chin Tan• Chen Le Tian• Chan Tin Lee
• Problem: This hash function value does not depend on positions of characters! – Bad
[CS1020 Lecture 13: Hashing]
Hashing of strings (4/4)• A better hash function for strings is to “shift” the sum after each
character, so that the positions of the characters affect the hash value.
hash(s)sum = 0for each character c in s {
sum = sum*31 + c}return sum % m // m is the hash table size
Java’s String.hashCode() uses *31 as well.
[CS1020 Lecture 13: Hashing]
Implementing hash code: integers
Implementing hash code: booleans
Implementing hash code: doubles
Implementing hash code: doubles
Implementing hash code: String
hash & 0x7FFFFFFF
Implementing hash code: String
Example: Hash Function
0 1 2 3 4 5 6 7 8 9
12117สบ, ฿15
32621นำ, ฿10
15252จาน, ฿20
89133ชอน, ฿5
98105แกว, ฿18
§ จากตวอยาง key คอ รหสสนคา§ หา Hash(key) เพอแปลงไปเปน Index§ Hash(key) = key % 10
38227แปง, ฿25เกดการชนกน
§ จากตวอยาง key คอ รหสสนคา§ หา Hash(key) เพอแปลงไปเปน Index§ Hash(key) = (key/10 % 10) + (key % 10)
§ เมอตองรบประกนวาไมเกดการชนกน ตองรชดขอมลทงหมดกอน แลวหาสตรคำนวณทไมชนกน แตในทางปฏบต ไมสามารถรขอมลทงหมดได
Example: Hash Function
0 1 2 3 4 5 6 7 8 9
12117สบ, ฿15
32621นำ, ฿10
15252จาน, ฿20
89133ชอน, ฿5
98105แกว, ฿18
38227แปง, ฿25
Hash Table• array ทใช* hash function ในการคำนวณหา index ของ array เราเรยกวEา
hash table
• จากตวอยEาง ใช* id number ของพนกงานเปNนตวหา index
• index = number % size;
วธแก'ป)ญหา index ทซำกน (Collision)• การใช' Hash Function ทำให'ใช'เวลาในการค'นหาน'อยลง
• ป)ญหา อาจทำให'เกด index ทซำกนได' วธแก'ป)ญหามหลายวธ
• Open Addressing
• แตVละชVองในตารางเกบข'อมล
• ถ'าชน กหาชVองวVางใหมVในตารางเพอเกบข'อมล
• Linear Probing
• Quadratic Probing
• Double Hashing
• Separate Chaining
• แตVละชVองในตารางเกบรายการโยงของข'อมล
• ข'อมลทชนกนเกบอยVด'วยกน ไมVกระทบข'อมลอน
• เปลองตวโยง (links)
Linear Probing• หากเกดการชนจะเพมค0า index ทละ 1 ค0า จนกว0าจะเจอตำแหน0งว0าง
• ใหB hj(x) คอช0องท probe หลงจากชนครงท j
• h(x) = h0(x) คอ ช0องท hash เรมตBน ใชB h(x) = x % 13
• hj(x) = (h(x) + j) % size
• แลBวเพมขBอมลทมคยYตามลำดบดงน
17 32 26 7 4 43 12 11 24
0 1 2 3 4 5 6 7 8 9 10 11 1226 24 17 4 32 7 43 11 12
ข"อเสย Linear Probing• เมอข"อมลอย-รวมกนมาก ๆ (ด"วยค-า hash เดยวกน และ/หรอเมอมการเพม
ค-า index เพอหาทเกบข"อมลทว-างอย-) จะเกดการเกาะกล-มกน เรยกว-า
Primary Clustering
• การ probe จะมมากขนและเมอข"อมลถกลบออก การค"นหากมความซบซ"อน
มากยงขน
Quadratic Probing• เพอไม(ให+เกดการรวมกนของกล(มข+อมลท hash ลงทเดยวกน (clustering)
• กระจายข+อมลท hash ลงทเดยวกน ด+วยการใช+เลขยกกำลงสองเปQนตวกำหนด
index ของ hash table
• ให+ hj(x) = h0(x) คอช(องท probe หลงจากชนครงท j
• h(x) คอ ช(องท hash เรมต+น ใช+ h(x) = x % 13
• hj(x) = (h(x) + j2) % 13
• แล+วเพมข+อมลทมคยcตามลำดบดงน
17 32 26 7 4 44 12 11 24
0 1 2 3 4 5 6 7 8 9 10 11 1226 24 17 4 32 7 44 11 12
Exercise: Quadratic Probing• เพมข'อมลทมคย/ตามลำดบดงน20 10 30 50 40
เพมข'อมล 20 : h0(20) = (h(20) + 02) % 10 = 0 เพมข'อมล 10 : h0 (10) = (h(10) + 02) % 10 = 0 ชน
h1 (10) = (h(10) + 12) % 10 = 1เพมข'อมล 30 : h0 (30) = (h(30) + 02) % 10 = 0 ชน
h1 (30) = (h(30) + 12) % 10 = 1 ชนh2 (30) = (h(30) + 22) % 10 = 4
เพมข'อมล 50 : h0 (50) = (h(50) + 02) % 10 = 0 ชนh1 (50) = (h(50) + 12) % 10 = 1 ชนh2 (50) = (h(50) + 22) % 10 = 4 ชนh3 (50) = (h(50) + 32) % 10 = 9
เพมข'อมล 40 : h0 (40) = (h(40) + 02) % 10 = 0 ชนh1 (40) = (h(40) + 12) % 10 = 1 ชนh2 (40) = (h(40) + 22) % 10 = 4 ชนh3 (40) = (h(40) + 32) % 10 = 9 ชนh4 (40) = (h(50) + 42) % 10 = 6
0 1 2 3 4 5 6 7 8 9
Quadratic Probing• เพมข'อมล 30
• h(x) = h0(x) = x % 13 • hj(x) = (h(x) + j2) % 13เพมข'อมล 30 : h0 (30) = (h(30) + 02) % 13 = 4 ชน
h1 (30) = (h(30) + 12) % 13 = 5 ชนh2 (30) = (h(30) + 22) % 13 = 8 ชนh3 (30) = (h(30) + 32) % 13 = 0 ชนh4 (30) = (h(30) + 42) % 13 = 7 ชนh5 (30) = (h(30) + 52) % 13 = 3 ชนh6 (30) = (h(30) + 62) % 13 = 1 ชนh7 (30) = (h(30) + 72) % 13 = 1 ชนh8 (30) = (h(30) + 82) % 13 = 3 ชนh9 (30) = (h(30) + 92) % 13 = 7 ชนh10 (30) = (h(30) + 102) % 13 = 0 ชน
0 1 2 3 4 5 6 7 8 9 10 11 120 1 17 4 5 7 8
Double Hashing• กำหนดให'ม hash function อกตวหนง
• ข'อมลท hash ไปทชCองเดยวกน อาจมระยะกระโดดตCางกน (เพอไมCยำอยCกบท)
• hash function ตวน จะต'องไมCสร'าง index ท hash function ตวแรกได'สร'างไว'และจะต'องไมCสร'างคCาทเปWน 0 เพราะ จะทำให'การ probe เจอตำแหนCงทซำกนตลอดเวลา
• โดยทวไป hash function ตวท 2 มกใช'
g(x) = constant – (x % constant)
• โดยกำหนดให'คCา constant เปWนจำนวนเฉพาะ (prime) ทมขนาดเลกกวCาขนาดของ table เชCน
g(x) = 5 – (x % 5)
Double Hashing• h(x) = h0(x) = x % size
• hj(x) = (h(x) + j·g(x)) % zise
• g(x) = constant – (x % constant)
• โดยท constant เป?นจำนวนเฉพาะ (prime) และ มคOานPอยกวOา size
• Size เป?นจำนวนเฉพาะ
• ตวหารรOวมมากของ g(x) และ m มคOาเป?น 1
ตวอยOาง
• ถPา h(x) = 0, g(x) = 4 และ size = 8, จะไดP index คOา 0 และ 4 เทOานน
• ถPา h(x) = 0, g(x) = 4 และ size = 7, จะไดP index คOา 0, 4, 1, 5, 2, 6, 3
Double Hashing• เพมข'อมล 23
• h(x) = h0(x) = x % 7• hj(x) = (h(x) + j·g(x)) % 7• g(x) = 5 – (x % 5)เพมข'อมล 23 : h0 (23) = (h(23) + 0·g(23)) % 7 = 4 ชน
h1 (23) = (h(23) + 1·g(23)) % 7 = 2 ชนh2 (23) = (h(23) + 2·g(23)) % 7 = 0 ชน
h3 (23) = (h(23) + 3·g(23)) % 7 = 5 ชน
h4 (23) = (h(23) + 4·g(23)) % 7 = 3 ชนh5 (23) = (h(23) + 5·g(23)) % 7 = 1 ชนh6 (23) = (h(23) + 6·g(23)) % 7 = 6 ชน
0 1 2 3 4 5 614 29 9 65 18 5
Separate Chaining• อนญาตให)เกดการชนกนได)• จดเกบข)อมลทชนกนไว)ใน list เดยวกน
0
1
2
3
4
5
6
7
8
9
20 60
11
43
51
23
89 9 29 49
46
57
ตวอยางHash(x) = x % size
= x % 10
Separate Chaining• Hash: map key to integer i between 0 and M - 1.• Insert: put at front of ith chain (if not already there).• Search: need to search only ith chain.
Separate-chaining symbol table: Java implementation
Separate-chaining symbol table: Java implementation
ADT Table OperationsSorted Array
Balanced BST
Hashing
Insertion O(n) O(log n) O(1) avg
Deletion O(n) O(log n) O(1) avg
Retrieval O(log n) O(log n) O(1) avg
[CS1020 Lecture 13: Hashing]
Summary• How to hash? Criteria for good hash functions?• How to resolve collision?
Collision resolution techniques:• linear probing• quadratic probing• double hashing• separate chaining
• Problem on deletions• Primary clustering
[CS1020 Lecture 13: Hashing]
Class HashMap <K, V>
• This class implements a hash map, which maps keys to values. Any non-null object can be used as a key or as a value.
e.g. We can create a hash map that maps people names to their ages. It uses the names as keys, and the ages as the values.
• The AbstractMap is an abstract class that provides a skeletal implementation of the Mapinterface.
• Generally, the default load factor (0.75) offers a good tradeoff between time and space costs.
• The default HashMap capacity is 16.
public class HashMap<K,V>extends AbstractMap<K,V>implements Map<K,V>, Cloneable, Serializable
java.util.HaspMap
[CS1020 Lecture 13: Hashing]
• Constructors summary • HashMap()
Constructs an empty HashMap with a default initial capacity (16) and the default load factor of 0.75.
• HashMap(int initialCapacity)Constructs an empty HashMap with the specified initial capacity and the default load factor of 0.75.
• HashMap(int initialCapacity, float loadFactor)Constructs an empty HashMap with the specified initial capacity and load factor.
• HashMap(Map<? extends K, ? extends V> m)Constructs a new HashMap with the same mappings as the specified Map.
Class HashMap <K, V>
[CS1020 Lecture 13: Hashing]
java.util.HaspMap
Class HashMap <K, V>Some methods • void clear()
Removes all of the mappings from this map.
• boolean containsKey(Object key)Returns true if this map contains a mapping for the specified key.
• boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value.
• V get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the
key. • V put(K key, V value)
Associates the specified value with the specified key in this map. • ...
[CS1020 Lecture 13: Hashing]
java.util.HaspMap
Example• Example: Create a hashmap that maps people names to their ages. It uses names
as key, and the ages as their values.
The output of the above code is:Janet => 46
HashMap<String, Integer> hm = new HashMap<String, Integer>();
// placing items into the hashmap
hm.put("Mike", 52);
hm.put("Janet", 46);
hm.put("Jack", 46);
// retrieving item from the hashmap
System.out.println("Janet => " + hm.get("Janet"));
TestHash.java
[CS1020 Lecture 13: Hashing]
java.util.HaspMap
Example• Example: Create a hashmap that maps people names to their ages. It uses names
as key, and the ages as their values.
The output of the above code is:{Mike=52, Janet=46, Jack=46}
HashMap<String, Integer> hm = new HashMap<String, Integer>();
// placing items into the hashmap
hm.put("Mike", 52);
hm.put("Janet", 46);
hm.put("Jack", 46);
// print item from the hashmap
System.out.println(hm);
TestHash.java
[CS1020 Lecture 13: Hashing]
java.util.HaspMap