CSC 103 Lecture Notes Week 5
Hashing
[ "Baker", "Doe", "Jones", "Smith" ]
[ {"Baker, Mary", 51, 549886295, "123 Main St."}, {"Doe, John", 28, 861483372,"456 1st Ave."}, ... ]
class InformationRecord { String name; // Person name int age; // Age int id; // Unique id String address; // Home address }
Allocate an array of the desired table size and provide a function that maps any key into the range 0 to TableSize-1.
Figure 1: Hash table with entries at 6295 and 3372.
and then compute the modulus.char[0] + (27 * char[1]) + (729 * char[2])
where 37 is the empirically-derived constant and l = the string length of the key.(37 * char[0]) + (372 * char[1]) + ... + (37(l-1) * char[l])
/**** * * Class Hashing contains three different string-valued hash functions, as * discussed in Lecture Notes Week 5. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 1may01 */ public class Hashing { /** * Compute a hash index for the given string by summing the string * characters and taking the modulus of the given table size. */ public static int hash1(String key, int tableSize) { int hashVal = 0; for (int i = 0; i < key.length(); i++) { hashVal += key.charAt(i); } return hashVal % tableSize; } /** * Compute a hash index for the given string by summing the first three * string characters with the formula: * * char[0] + (27 * char[1]) + (729 * char[2]) * * where 27 is the number of letter in the alphabet + 1 for a blank, and * 729 is 27<sup>2</sup>. * * Return the sum mod the given table size. */ public static int hash2(String key, int tableSize) { int hashVal = 0; return (key.charAt(0) + (27 * key.charAt(1)) + (729 * key.charAt(2))) % tableSize; } /** * Compute a hash index for the given string by summing all of the string * characters with the formula: * * (37 * char[0]) + (37^2 * char[1]) + ... + (37^(l-1) * char[l]) * * where 37 is an empirically chosen value to provide good distribution and * l = key.length(). * * Return the sum mod the given table size. */ public static int hash3(String key, int tableSize) { int hashVal = 0; for (int i = 0; i < key.length(); i++) { hashVal = 37 * hashVal + key.charAt(i); } hashVal %= tableSize; if (hashVal < 0) { hashVal += tableSize; } return hashVal; } }