CS 2430 Day 34 Announcements • No office hours tomorrow • Lab tomorrow (graphics, keyboard, mouse input) • Quiz this Friday • Exam #3: 12/12/12 Agenda • Linear probe (review) • Quadratic probe • Double hash Linear probe • • • • Table size = 11 Hash function: H(x) = x % 11 Next index function: f(n) = n In the event of a collision, we use: H(x + n) = (x + n) % 11, where we increment n for each collision (starting from 0) Linear probe example H(x H(x H(x H(x H(x H(x) + 1) + 2) + 3) + 4) + 5) = = = = = = (x (x (x (x (x + + + + + x 1) 2) 3) 4) 5) % % % % % % 11 11 11 11 11 11 55 23 45 86 0 1 2 3 8 23 32 45 55 75 86 8 1 10 1 2 0 9 9 10 0 1 2 3 8 75 32 8 9 10 4 5 6 7 Next: quadratic probing Quadratic probe • • • • Table size = 11 (should always be prime) Hash function: H(x) = x % 11 Next index function: f(n) = n2 For collisions, we use H(x + n2) = (x + n2) % 11 Quadratic probe example H(x) H(x + 12) H(x + 22) H(x + 32) = = = = x (x + 1) (x + 4) (x + 9) 55 23 45 0 1 2 % % % % 11 11 11 11 3 8 23 32 45 55 75 86 8 1 10 1 2 0 9 9 10 2 7 86 8 75 32 7 8 9 10 4 5 6 A full table! • For linear probing, it is a bad idea to let the hash table get nearly full • For quadratic probing, the situation is much more drastic! A drastic situation • Fact: if quadratic probing is used and the table size is prime, then a new object can always be added if the table is at least half empty • That is, if the table is more than half full, then it is not always possible to add a new object. • Why? • Think about it… Go to THE THING: https://xray.ion.uwplatt.edu/summerss Double hashing • Table size = 11 • Hash function: H(x) = x % 11 • Next index function: f(n) = cn, where c is the “hashing constant” • For collisions, we use H(x + cn) = (x + cn) % 11 • In our example, we will let c = 3 Double hash example H(x) H(x + 3*1) H(x + 3*2) H(x + 3*3) = = = = x (x + 3) (x + 6) (x + 9) 55 23 0 1 % % % % 11 11 11 11 8 23 32 45 55 75 86 8 1 10 1 4 0 9 9 1 4 7 86 8 75 32 7 8 9 10 45 2 3 4 5 6 Important • For double hashing, the table size and the hashing constant, c, must be relatively prime • Why? • Not every array location will be searched! Double hash disaster!! H(x H(x H(x H(x H(x H(x + + + + + + H(x) 3*1) 3*2) 3*3) 3*4) 3*5) 3*6) = = = = = = = x (x + 3) (x + 6) (x + 9) (x + 12) (x + 15) (x + 18) % % % % % % % 11 11 11 11 11 11 11 2 5 8 11 2 5 8 2 5 8 2 5 8 2 2 0 1 2 5 3 4 5 8 6 7 8 Go to THE THING: https://xray.ion.uwplatt.edu/summerss