Dictionaries 4/1/2017 2:36 PM Hash Tables  1 2 3 4 …

Slides:



Advertisements
Similar presentations
Chapter 11. Hash Tables.
Advertisements

David Luebke 1 6/7/2014 ITCS 6114 Skip Lists Hashing.
© 2004 Goodrich, Tamassia Hash Tables
1 Hash Tables Saurav Karmakar. 2 Motivation What are the dictionary operations? What are the dictionary operations? (1) Insert (1) Insert (2) Delete (2)
1 Designing Hash Tables Sections 5.3, 5.4, Designing a hash table 1.Hash function: establishing a key with an indexed location in a hash table.
CSCI 2720 Hashing   Spring 2005.
Hash Table.
Briana B. Morrison Adapted from William Collins
© 2004 Goodrich, Tamassia Hash Tables
Hash Tables.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Hash Tables Introduction to Algorithms Hash Tables CSE 680 Prof. Roger Crawfis.
Hashing as a Dictionary Implementation
© 2004 Goodrich, Tamassia Hash Tables1  
Hashing Chapters What is Hashing? A technique that determines an index or location for storage of an item in a data structure The hash function.
Chapter 9: Maps, Dictionaries, Hashing Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University Acknowledgement: These slides are adapted from slides provided.
Maps. Hash Tables. Dictionaries. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
Data Structures Lecture 12 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Log Files. O(n) Data Structure Exercises 16.1.
CSC401 – Analysis of Algorithms Lecture Notes 5 Heaps and Hash Tables Objectives: Introduce Heaps, Heap-sorting, and Heap- construction Analyze the performance.
Dictionaries and Hash Tables1  
1 Chapter 9 Maps and Dictionaries. 2 A basic problem We have to store some records and perform the following: add new record add new record delete record.
Hash Tables1 Part E Hash Tables  
Hash Tables1 Part E Hash Tables  
Hash Tables1 Part E Hash Tables  
Dictionaries 4/17/2017 3:23 PM Hash Tables  
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Maps, Dictionaries, Hashing
1. 2 Problem RT&T is a large phone company, and they want to provide enhanced caller ID capability: –given a phone number, return the caller’s name –phone.
CS 221 Analysis of Algorithms Data Structures Dictionaries, Hash Tables, Ordered Dictionary and Binary Search Trees.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
1 HashTable. 2 Dictionary A collection of data that is accessed by “key” values –The keys may be ordered or unordered –Multiple key values may/may-not.
Hash Tables1   © 2010 Goodrich, Tamassia.
Dictionaries and Hash Tables1 Hash Tables  
© 2004 Goodrich, Tamassia Hash Tables1  
Chapter 10 Hashing. The search time of each algorithm depend on the number n of elements of the collection S of the data. A searching technique called.
Chapter 11 Hash Tables © John Urrutia 2014, All Rights Reserved1.
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
CHAPTER 9 HASH TABLES, MAPS, AND SKIP LISTS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++,
1 the hash table. hash table A hash table consists of two major components …
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Prof. Amr Goneid, AUC1 CSCI 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 5. Dictionaries(2): Hash Tables.
Lecture14: Hashing Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Hash Maps Rem Collier Room A1.02 School of Computer Science and Informatics University College Dublin, Ireland.
Algorithms Design Fall 2016 Week 6 Hash Collusion Algorithms and Binary Search Trees.
Hash Tables 1/28/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Hashing (part 2) CSE 2011 Winter March 2018.
Hashing CSE 2011 Winter July 2018.
Dictionaries and Hash Tables
Dictionaries Dictionaries 07/27/16 16:46 07/27/16 16:46 Hash Tables 
© 2013 Goodrich, Tamassia, Goldwasser
Dictionaries 9/14/ :35 AM Hash Tables   4
Hash Tables 3/25/15 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Searching.
Data Structures Maps and Hash.
Hash Tables 11/22/2018 3:15 AM Hash Tables  1 2  3  4
Dictionaries 11/23/2018 5:34 PM Hash Tables   Hash Tables.
Dictionaries and Hash Tables
Copyright © Aiman Hanna All rights reserved
Hash Tables   Maps Dictionaries 12/7/2018 5:58 AM Hash Tables  
CH 9.2 : Hash Tables Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and.
Dictionaries and Hash Tables
Dictionaries 1/17/2019 7:55 AM Hash Tables   4
CH 9.2 : Hash Tables Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and.
Hash Tables Computer Science and Engineering
Hash Tables Computer Science and Engineering
Hash Tables Computer Science and Engineering
Dictionaries 4/5/2019 1:49 AM Hash Tables  
CS210- Lecture 16 July 11, 2005 Agenda Maps and Dictionaries Map ADT
Dictionaries and Hash Tables
Presentation transcript:

Dictionaries 4/1/2017 2:36 PM Hash Tables  1 2 3 4 451-229-0004 981-101-0002 025-612-0001 451-229-0004 981-101-0002 200-751-9998 025-612-0001 … Helen, 40, Taipei, … Gary, 35, Yunlin, … Many, 20, Chiayi, … Tom, 30, Douliou, … How to store and retrieve a set of key-value pairs? key value implemenation by link list

Recall the Map ADT Map ADT methods: Dictionaries Recall the Map ADT 4/1/2017 2:36 PM Map ADT methods: size(), isEmpty() get(k): if the map M has an entry with key k, return its assoiciated 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 keys(): return an iterator of the keys in M values(): return an iterator of the values in M Disadvantage with list-based implementation Map: Key-value entries (k1, v1), (k2, v2), (k3, v3), …

To store and retrieve entries: Example of Hashing We design a hash table for a map storing entries as (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(k) = last four digits of k  1 2 3 4 9997 9998 9999 … 451-229-0004 981-101-0002 200-751-9998 025-612-0001 To store and retrieve entries: 451-229-0004 981-101-0002 200-751-9998 025-612-0001 … h(k) hash table

Hash Functions and Hash Tables Dictionaries Hash Functions and Hash Tables 4/1/2017 2:36 PM A hash function h maps keys of a given type to integers in a fixed interval [0, N - 1] i = h(k) 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 Array (called table) of size N Hash function h When implementing a map with a hash table, the goal is to store item (k, o) at index i = h(k)

Dictionaries 4/1/2017 2:36 PM

Hash Functions Hash code: h1: keys  integers Dictionaries Hash Functions 4/1/2017 2:36 PM The hash code is applied first, and the compression function is applied next on the result, i.e., h(k) = h2(h1(k)) The goal of the hash function is to “disperse” the keys in an apparently random way A hash function is usually specified as the composition of two functions: Hash code: h1: keys  integers Compression function: h2: integers  [0, N - 1] i = h(k) y = h1(key) h2(y)

Various Hash Codes Memory address: Integer cast: Component sum: Dictionaries Various Hash Codes 4/1/2017 2:36 PM 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) E.g. Float.floatToIntBits(x) for a variable x of base type float 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) static int hashCode(long i) {return (int)((i >> 32) + (int) i);}

Polynomial Hash Codes Polynomial accumulation: Dictionaries Polynomial Hash Codes 4/1/2017 2:36 PM Polynomial accumulation: We partition the bits of the key into a sequence of components of fixed length (e.g., 8, 16 or 32 bits) x0 x1 … xk-1 We evaluate the polynomial p(a) = x0 ak-1+ x1 ak-2 + … xk-2 a + xk-1 at a fixed value a, ignoring overflows Especially suitable for strings (e.g., the choice a = 33 gives at most 6 collisions on a set of 50,000 English words) Polynomial p(a) 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(a) = x0 pi (a) = xi + api-1(a) (i = 1, 2, …, k -1) We have p(a) = pk-1(a) Tom Mary Helen John ‘T’(33)2+’o’(33)1+’m’

Cyclic Shift Hash Codes Dictionaries Cyclic Shift Hash Codes 4/1/2017 2:36 PM A variant of the polynomial hash code replaces multiplication by a with a cyclic shift of a partial sum by a certain number of bits. static int hashCode(String s) { int h=0; for (int i=0; i<s.length(); i++) { h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of the running sum h += (int) s.charAt(i); // add in next character } return h; Note: “<<” cyclic left shift “>>>” shift bits right, filling in with zeros

Dictionaries 4/1/2017 2:36 PM Note: 5-bit cyclic shift has the best performance for a list over 25,000 English words 5-bit

Compression Functions Dictionaries 4/1/2017 2:36 PM Compression Functions y = h1(key) 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 Multiply, Add and Divide (MAD): h2 (y) = [(ay + b) mod p] mod N p is a prime number larger than N a and b are integers chosen at random from [0, p1], with a > 0 h2(y)

Collision Handling Collisions occur when different elements are mapped to the same cell, i.e., h(k1) = h(k2) Solutions separate chaining open addressing (i.e., find a different cell) linear probing quadratic probling double hashing 1 2 3 4 025-612-0001 h(k1) 451-229-0004 981-101-0004 h(k2)

Dictionaries Separate Chaining 4/1/2017 2:36 PM 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 h(k) = k mod 13

Map Methods with Separate Chaining used for Collisions Dictionaries 4/1/2017 2:36 PM Map Methods with Separate Chaining used for Collisions Algorithm get(k): Output: The value associated with the key k in the map, or null if there is no entry with key equal to k in the map return A[h(k)].get(k) {delegate the get to the list-based map at A[h(k)]} Algorithm put(k,v): Output: If there is an existing entry in our map with key equal to k, then we return its value (replacing it with v); otherwise, we return null t = A[h(k)].put(k,v) {delegate the put to the list-based map at A[h(k)]} if t = null then {k is a new key} n = n + 1 return t Algorithm remove(k): Output: The (removed) value associated with key k in the map, or null if there is no entry with key equal to k in the map t = A[h(k)].remove(k) {delegate the remove to the list-based map at A[h(k)]} if t ≠ null then {k was found} n = n - 1

Dictionaries Linear Probing 4/1/2017 2:36 PM h(k) = k mod 11 k = 15

Linear Probing Example: Dictionaries Linear Probing 4/1/2017 2:36 PM 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; that is, the order of A[i], A[(i+1) mod N], A[(i+2) mod N], … where i = h(k) Example: h(k) = k 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

Search with Linear Probing Dictionaries Search with Linear Probing 4/1/2017 2:36 PM 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 Algorithm get(k) i  h(k) p  0 repeat c  A[i] if c =  return null else if c.key () = k return c.element() else i  (i + 1) mod N p  p + 1 until p = N

Updates with Linear Probing Dictionaries Updates with Linear Probing 4/1/2017 2:36 PM To handle insertions and deletions, we introduce a special object, called AVAILABLE, which replaces deleted elements remove(k) We search for an entry with key k If such an entry (k, o) is found, we replace it with the special item AVAILABLE and we return element o Else, we return null put(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 entry (k, o) in cell i remove(22) 41 18 44 59 22 1 2 3 4 5 6 7 8 9 10 11 12

Quadratic Probing Iteratively trying the buskets Dictionaries Quadratic Probing 4/1/2017 2:36 PM Iteratively trying the buskets A[(i+f(j)) mod N], for j = 0, 1, 2, …, where f(j) = j2 Example: h(k) = k 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 31 41 18 44 59 73 22 32 quadratic probing linear probing

A[(i + f(j)) mod N] for j = 1, 2, 3, …, where f(j) = j*h’(k). Dictionaries Double Hashing 4/1/2017 2:36 PM If A[i], with i = h(k) is already occupied, double hashing uses a secondary hash function h’(k) and handles collisions by placing an item in the first available cell of the series The secondary hash function h’(k) cannot have zero values The table size N must be a prime to allow probing of all the cells Common choice of compression function for the secondary hash function: h’(k) = q - (k mod q) where q < N and q is a prime The possible values for h’(k) are 1, 2, … , q A[(i + f(j)) mod N] for j = 1, 2, 3, …, where f(j) = j*h’(k). Collision handling: A[(i + f(j)) mod N] where i = h(k) for j = 1, 2, 3, …, where f(j) = j*h’(k)

Example of Double Hashing Dictionaries Example of Double Hashing 4/1/2017 2:36 PM Consider a hash table storing integer keys that handles collision with double hashing N = 13 h(k) = k mod 13 h’(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 Collision handling: A[(i + f(j)) mod N] where i = h(k) for j = 1, 2, 3, …, where f(j) = j*h’(k) h’(k) = q - (k mod q) where q < N and q is a prime

Performance of Hashing Dictionaries Performance of Hashing 4/1/2017 2:36 PM 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 map collide The load factor  = n/N affects the performance of a hash table Suggest:  < 0.5 for open addressing schemes and  < 0.9 for separate chaining If load factor goes significantly above the threshold, then rehashing to a new table is performed 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-) ) 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 1 … … n  = n/N Hashing

9.2.6 A Java Hash Table Implementation Dictionaries 9.2.6 A Java Hash Table Implementation 4/1/2017 2:36 PM /** A hash table with linear probing and the MAD hash function */ import java.util.Iterator; public class HashTableMap<K,V> implements Map<K,V> { public static class HashEntry<K,V> implements Entry<K,V> { protected K key; protected V value; public HashEntry(K k, V v) { key = k; value = v; } public V getValue() { return value; } public K getKey() { return key; } public V setValue(V val) { V oldValue = value; value = val; return oldValue; } public boolean equals(Object o) { HashEntry<K,V> ent; try { ent = (HashEntry<K,V>) o; } catch (ClassCastException ex) { return false; } return (ent.getKey() == key) && (ent.getValue() == value);

protected int n = 0; // number of entries in the dictionary Dictionaries 4/1/2017 2:36 PM protected Entry<K,V> AVAILABLE = new HashEntry<K,V>(null, null); // marker protected int n = 0; // number of entries in the dictionary protected int capacity; // capacity of the bucket array protected Entry<K,V>[] bucket; // bucket array protected int scale, shift; // the shift and scaling factors /** Creates a hash table with initial capacity 1023. */ public HashTableMap() { this(1023); } /** Creates a hash table with the given capacity. */ public HashTableMap(int cap) { capacity = cap; bucket = (Entry<K,V>[]) new Entry[capacity]; // safe cast java.util.Random rand = new java.util.Random(); scale = rand.nextInt(capacity-1) + 1; shift = rand.nextInt(capacity); } /** Determines whether a key is valid. */ protected void checkKey(K k) { if (k == null) throw new InvalidKeyException("Invalid key: null."); /** Hash function applying MAD method to default hash code. */ public int hashValue(K key) { return (int) ((Math.abs(key.hashCode()*scale + shift) % prime) % capacity);

/** Returns the number of entries in the hash table. */ Dictionaries 4/1/2017 2:36 PM /** Returns the number of entries in the hash table. */ public int size() { return n; } /** Returns whether or not the table is empty. */ public boolean isEmpty() { return (n == 0); } /** Returns an iterable object containing all of the keys. */ public Iterable<K> keys() { PositionList<K> keys = new NodePositionList<K>(); for (int i=0; i<capacity; i++) if ((bucket[i] != null) && (bucket[i] != AVAILABLE)) keys.addLast(bucket[i].getKey()); return keys; }

Dictionaries /** Helper search method - returns index of found key or -(a + 1), * where a is the index of the first empty or available slot found. */ protected int findEntry(K key) throws InvalidKeyException { int avail = -1; checkKey(key); int i = hashValue(key); int j = i; do { Entry<K,V> e = bucket[i]; if ( e == null) { if (avail < 0) avail = i; // key is not in table break; } if (key.equals(e.getKey())) // we have found our key return i; // key found if (e == AVAILABLE) { // bucket is deactivated avail = i; // remember that this slot is available i = (i + 1) % capacity; // keep looking } while (i != j); return -(avail + 1); // first empty or available slot 4/1/2017 2:36 PM findEntry(15)

/** Returns the value associated with a key. */ Dictionaries /** Returns the value associated with a key. */ public V get (K key) throws InvalidKeyException { int i = findEntry(key); // helper method for finding a key if (i < 0) return null; // there is no value for this key return bucket[i].getValue(); // return the found value in this case } /** Put a key-value pair in the map, replacing previous one if it exists. */ public V put (K key, V value) throws InvalidKeyException { int i = findEntry(key); //find the appropriate spot for this entry if (i >= 0) // this key has a previous value return ((HashEntry<K,V>) bucket[i]).setValue(value); // set new value if (n >= capacity/2) { rehash(); // rehash to keep the load factor <= 0.5 i = findEntry(key); //find again the appropriate spot for this entry bucket[-i-1] = new HashEntry<K,V>(key, value); // convert to proper index n++; return null; // there was no previous value 4/1/2017 2:36 PM put(15, Value)

/** Removes the key-value pair with a specified key. */ Dictionaries 4/1/2017 2:36 PM /** Doubles the size of the hash table and rehashes all the entries. */ protected void rehash() { capacity = 2*capacity; Entry<K,V>[] old = bucket; bucket = (Entry<K,V>[]) new Entry[capacity]; // new bucket is twice as big java.util.Random rand = new java.util.Random(); scale = rand.nextInt(capacity-1) + 1; // new hash scaling factor shift = rand.nextInt(capacity); // new hash shifting factor for (int i=0; i<old.length; i++) { Entry<K,V> e = old[i]; if ((e != null) && (e != AVAILABLE)) { // a valid entry int j = - 1 - findEntry(e.getKey()); bucket[j] = e; } /** Removes the key-value pair with a specified key. */ public V remove (K key) throws InvalidKeyException { int i = findEntry(key); // find this key first if (i < 0) return null; // nothing to remove V toReturn = bucket[i].getValue(); bucket[i] = AVAILABLE; // mark this slot as deactivated n--; return toReturn;

9.2.8 Applications: Counting Word Frequencies in a Document Dictionaries 4/1/2017 2:36 PM 9.2.8 Applications: Counting Word Frequencies in a Document import java.io.*; import java.util.Scanner; import net.datastructures.*; /** A program that counts words in a document, printing the most frequent. */ public class WordCount { public static void main(String[] args) throws IOException { Scanner doc = new Scanner(System.in); doc.useDelimiter("[^a-zA-Z]"); // ignore non-letters; any characters except a-zA-Z HashTableMap<String,Integer> h = new HashTableMap<String,Integer>(); String word; Integer count; Entry: (word, count)

9.2.8 Applications: Counting Word Frequencies Dictionaries 9.2.8 Applications: Counting Word Frequencies 4/1/2017 2:36 PM while (doc.hasNext()) { word = doc.next(); if (word.equals("")) continue; // ignore null strings between delimiters word = word.toLowerCase(); // ignore case count = h.get(word); // get the previous count for this word if (count == null) h.put(word, 1); // autoboxing allows this else h.put(word, ++count); // autoboxing/unboxing allows this } int maxCount = 0; String maxWord = "no word"; for (Entry<String,Integer> ent : h.entries()) { // find max-count word if (ent.getValue() > maxCount) { maxWord = ent.getKey(); maxCount = ent.getValue(); System.out.print("The most frequent word is \"" + maxWord); System.out.println(",\" with word-count = " + maxCount + ".");