Hash table

# Hash table - Hash Tables Goal access item given its key(not...

This preview shows pages 1–5. Sign up to view the full content.

Chapter 9: Sets and Maps 1 Hash Tables Goal: access item given its key (not its position ) Therefore, want to locate it directly from the key In other words, we wish to avoid much searching Hash tables provide this capability Constant time in the average case! O(1) Linear time in the worst case O(n) Searching an array: O(n) Searching BST: O(log n)

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

View Full Document
Chapter 9: Sets and Maps 2 Hash Codes Suppose we have a table of size N A hash code is: A number in the range 0 to N-1 We compute the hash code from the key You can think of this as a “default position” when inserting, or a “position hint” when looking up A hash function is a way of computing a hash code Desire: The set of keys should spread evenly over the N values When two keys have the same hash code: collision
Chapter 9: Sets and Maps 3 A Simple Hash Function Want to count occurrences of each Unicode character in a file There are 2 16 possible characters, but . .. Maybe only 100 or so occur in a given file Approach: hash character to range 0-199 That is, use a hash table of size 200 A possible hash function for this example: int hash = uni_char % 200; Collisions are certainly possible (see later)

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

View Full Document
Chapter 9: Sets and Maps 4 Devising Hash Functions Simple functions often produce many collisions ... but complex functions may not be good either! It is often an empirical process Adding letter values in a string: same hash for strings with same letters in different order Better approach: size_t hash = 0; for (size_t i = 0; i < s.size(); ++i) hash = hash * 31 + s[i]; This is the hash function used by Java in its String class.
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 10/31/2010 for the course EE 423 taught by Professor Mitin during the Spring '10 term at SUNY Buffalo.

### Page1 / 19

Hash table - Hash Tables Goal access item given its key(not...

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

View Full Document
Ask a homework question - tutors are online