Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hash Tables 11/22/2018 3:15 AM Hash Tables  1 2  3  4

Similar presentations


Presentation on theme: "Hash Tables 11/22/2018 3:15 AM Hash Tables  1 2  3  4 "— Presentation transcript:

1 Hash Tables 11/22/2018 3:15 AM Hash Tables 1 2 3 4 11/22/2018 3:15 AM Hash Tables

2 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 11/22/2018 3:15 AM Hash Tables

3 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. 11/22/2018 3:15 AM Hash Tables

4 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; …. 11/22/2018 3:15 AM Hash Tables

5 Suppose: Where are they located
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, ); solarSystem[h(“Jupiter”)] = new planet(“Jupiter”, 16, ); solarSystem[h(“Saturn”)] = new planet(“Saturn”, 12, ); solarSystem[h(“Uranus”)] = new planet(“Uranus”, 5, ); solarSystem[h(“Neptune”)] = new planet(“Neptune”, 2, 2795); solarSystem[h(“Pluto”)] = new planet(“Pluto”, 1, 3675); Where are they located 11/22/2018 3:15 AM Hash Tables

6 “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)]; } 11/22/2018 3:15 AM Hash Tables

7 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] 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: Chaining: colliding items are stored in a sequence Open addressing: the colliding item is placed in a different cell of the table 11/22/2018 3:15 AM Hash Tables

8 Example 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 1 2 3 4 9997 9998 9999 11/22/2018 3:15 AM Hash Tables

9 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] 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 11/22/2018 3:15 AM Hash Tables

10 Hash Code Maps Memory address: Integer cast: Component sum:
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) 11/22/2018 3:15 AM Hash Tables

11 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) 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/22/2018 3:15 AM Hash Tables

12 Compression Maps Division: Multiply, Add and Divide (MAD):
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 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 11/22/2018 3:15 AM Hash Tables

13 Linear Probing Example:
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 this order 1 2 3 4 5 6 7 8 9 10 11 12 41 18 44 59 32 22 31 73 1 2 3 4 5 6 7 8 9 10 11 12 11/22/2018 3:15 AM Hash Tables

14 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 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 11/22/2018 3:15 AM Hash Tables

15 Updates with Linear Probing
To handle insertions and deletions, we introduce a special object, called AVAILABLE, which replaces deleted elements removeElement(k) 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 insert Item(k, o) 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 11/22/2018 3:15 AM Hash Tables

16 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 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 11/22/2018 3:15 AM Hash Tables

17 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 1 2 3 4 5 6 7 8 9 10 11 12 31 41 18 32 59 73 22 44 1 2 3 4 5 6 7 8 9 10 11 12 11/22/2018 3:15 AM Hash Tables

18 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- )) 11/22/2018 3:15 AM Hash Tables

19 Performance: The expected length of an unsuccessful search is approximately: lengthunsucc = ½( 1 + 1/(1 - )2) 11/22/2018 3:15 AM Hash Tables

20 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. 11/22/2018 3:15 AM Hash Tables

21 Collision resolution using Linked Lists:
Dynamically allocate space. Easy to insert/delete an item Need a link for each node in the hash table. 11/22/2018 3:15 AM Hash Tables

22 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 11/22/2018 3:15 AM Hash Tables

23 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 a = 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 - a) 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 11/22/2018 3:15 AM Hash Tables

24 Locators 3 a 1 g 4 e 11/22/2018 3:15 AM Hash Tables Hash Tables

25 Outline and Reading Locators (§8.7) Locator-based methods
Implementation Positions vs. Locators 11/22/2018 3:15 AM Hash Tables

26 Locators Application example:
Hash Tables 11/22/2018 3:15 AM 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: claim check reservation number Methods of the locator ADT: key(): returns the key of the item associated with the locator element(): returns the element of the item associated with the locator Application example: 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 When an order is placed, a locator to it is returned Given a locator, an order can be canceled or modified 11/22/2018 3:15 AM Hash Tables

27 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 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) 11/22/2018 3:15 AM Hash Tables

28 Implementation The locator is an object storing
key element position (or rank) of the item in the underlying structure In turn, the position (or array cell) stores the locator Example: binary search tree with locators 6 d 3 a 9 b 1 g 4 e 8 c 11/22/2018 3:15 AM Hash Tables

29 Positions vs. Locators Position
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 Locator 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 11/22/2018 3:15 AM Hash Tables


Download ppt "Hash Tables 11/22/2018 3:15 AM Hash Tables  1 2  3  4 "

Similar presentations


Ads by Google