(16) Hashing

# (16) Hashing - Reading CMSC 132 Object-Oriented Programming...

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

1 CMSC 132: Object-Oriented Programming II Hashing Department of Computer Science University of Maryland, College Park Reading Read Sections 9.3-9.6 in the Koffman text (Sections 7.3-7.7 in the second edition) 3 Hashing A hash function is a function that maps data to a value (e.g., an integer) A hash code or hash value is the value returned by a hash function Approach: use a hash function to convert a key into a number (hash value) to be used as an index into a hash table (array) 4 Hashing Consider a hash table A with size N The indices of A range from 0 to N ± 1 The hash function value must be reduced to 0. .N – 1 The modulus operator can be used, so the hash value could just be Math.abs(keyValue % N)

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

View Full Document
5 Hash function Example- suppose: hash("apple") = 5 hash("fig") = 3 hash("banana") = 6 hash("kiwi") = 4 hash("blueberry") = 9 hash("honeydew") = 8 A perfect hash function produces a unique value for each key fig apple banana honeydew blueberry 0 1 2 3 4 5 6 7 8 9 kiwi 6 Hash function Example problem: assign four parking spaces (which have the numbers 0 through 3) to four people, using their ID number as a key, using the hash function h(key) = key % 4 What happens if two people happen to have IDs 123456780 and 123456784? This is called a collision , meaning that multiple keys have the same hash value 7 Hash function Suppose now: hash("apple") = 5 hash("fig") = 3 hash("banana") = 6 hash("kiwi") = 4 hash("blueberry") = 9 hash("honeydew") = 8 hash(“orange") = 5 Collision fig apple banana honeydew blueberry 0 1 2 3 4 5 6 7 8 9 kiwi 8 Collisions Collisions can be handled in several ways: Bucket or chained hashing Linear probing Double hashing
9 Chained hashing In chained hashing each element of the hash table doesn't store just a single value, but a

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 6

(16) Hashing - Reading CMSC 132 Object-Oriented Programming...

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

View Full Document
Ask a homework question - tutors are online