Unit08B - Hashing Sets & Maps Hash tables 8B Data records...

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

View Full Document Right Arrow Icon
1 Sets & Maps Hash tables 8B 2 Hashing Data records are stored in a hash table . The position of a data record in the hash table is determined by its key . A hash function maps keys to positions in the hash table. If a hash function maps two keys to the same position in the hash table, then a collision occurs. 3 Example Let the hash table be an 11-element array. If k is the key of a data record, let H(k) represent the hash function, where H(k) = k mod 11. Insert the keys 83, 14, 29, 70, 10, 55, 72: 0 1 2 3 4 5 6 7 8 9 10 Inserting 72 now would cause a collision! 83 14 29 70 55 10 4 Goals of Hashing An insert without a collision takes O(1) time. A search also takes O(1) time, if the record is stored in its proper location (without a collision). The hash function can take many forms: - If the key k is an integer: k % tablesize - If key k is a String (or any Object): k.hashCode() % tablesize - Any function that maps k to a table position! The table size should be a prime number. 5 Hash Codes for Strings Each character in a string has a unicode (int) value. 'A'=65 'B'=66 'C'=67, . .., 'a'=97, 'b'=98, 'c'=99, . .. Summing up the int values of the characters can lead to a lot of collisions: "Act" "Cat" "Ads" sum of char codes = 280 The hashcode method of the String class returns s 0 × 31 n-1 + s 1 × 31 n-2 + . .. + s n-1 for the string s 0 s 1 ...s n-1 String: "Act" "Cat" "Ads" hashcode: 65650 67510 67602 6 Birthday Paradox: A Hashing Function Let k be a birthday.
Background image of page 1

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

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

This note was uploaded on 12/19/2009 for the course CS 121 taught by Professor Reid-miller during the Spring '09 term at Carnegie Mellon.

Page1 / 4

Unit08B - Hashing Sets & Maps Hash tables 8B Data records...

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

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