Hash Tables-Implementation

Hash Tables-Implementation - Lecture 23: Implementing A...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 23: Implementing A Hash Table PIC 10B Todd Wittman Review: The Hash Concept s A hash table is a fixed size list of records organized according to a unique key. s The key is usually one of the data fields in the record. s Each block of the hash table is called a bucket . s Buckets may be empty, so the hash table wastes memory. s The hash function maps the record's key to an integer called the hash index . This tells us which bucket to put the record into. 2 Darth 1 Leia 4 C3PO 6 Yoda 357 Luke 359 Han 360 Chewie 0 1 2 3 4 5 6 357 358 359 360 361 499 ... ... s If every key maps to a unique hash index, then the hash table operations are very fast. O(1) O(1) O(1) Insert Erase Search
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 s But it is very difficult to map each key to a unique hash index. s A collision occurs when two keys are mapped to the same hash index. s One way to resolve collisions is to allow each bucket to store multiple records. This is called chaining . s Let k = maximum # of records stored in one bucket. 2 Darth 1 Leia 4 C3PO 6 Yoda 0 1 2 3 4 5 6 7 499 ... 4 R2D2 O(1) O(k) O(k) Insert Erase Search 4 Han 2 Lando Total # collisions = 4 k = 3 6 Obi If implemented with vectors. .. Templating Our HashTable Class s The other containers we built (LinkedList, Tree) could hold any type. s But to be stored in a hash table, the data type must have a key associated with it. s Also, we must have a way to hash that key to an integer index. s We will build our HashTable class on 2 templated types: b T -- the data type of the record we will store b K -- the data type of the key s We will assume that the record class T we are storing has the following 3 member functions: b K getKey () -- returns the key of the record b void setKey (K key) -- sets the key of the record b int getHash (int M) -- gets the hash index of the record, based on the hash table size M
Background image of page 2
3 Example: The Record Class s Suppose student records at Jedi Academy are indexed by the student name, e.g. "Luke Skywalker". class Record {
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 8

Hash Tables-Implementation - Lecture 23: Implementing A...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online