// Example 'good' hash function (modified slightly from p. 157) public int hash( String key, int tableSize ) { int hashVal = 0; for (int i = 0; i < key.length(); i++) hashVal = 37 * hashVal + key.charAt( i ); return Math.abs(hashVal % tableSize); // a value between 0 and (tableSize-1) }
public class Person { public Person(String fn, String ln, int a) { fname = fn; lname = ln; age = a; } public int hashcode() { String fullname = fname + " " + lname; return fullname.hashCode(); // hashCode() in String class -- // fullname's hash code is the // hash code of a Person } private String fname; // first name of a person private String lname; // last name of a person private int age; // age of a person }
Example:
Assume the type of X is int, M is 10, and the hash function returns X % M.
With this scheme, no item is physically removed until array is rehashed.
NOTE: Any non-null slot that is marked deleted can NOT be re-used
by insertion (except for the case when the same item is re-inserted) --
WHY??
Primary Clustering problem
|
e.g. Initial table M = 5, maximum load factor = 0.75
Let λ be the load factor.
Successful Search: | ![]() |
Unsuccessful Search: | ![]() |
Insert: | ![]() |
Some examples:
λ insert/unsuccessful find successful find 0.1 0.25 0.5 0.75 0.9
- So, the average-case complexity for insert and (both) find are O(1), irrespective of n.
- How about the worst-case complexity??
- insert
- unsuccessful find
- successful find
Secondary Clustering problem
|
Let λ be the load factor.
Successful Search: | ![]() |
Unsuccessful Search: | λ |
Insert: | λ , same as unsuccessful search |
IMPORTANT NOTES: