@@ -36,7 +36,7 @@ We could implement the Map ADT with AVL Trees, then `get()` is O(log(n)).
3636
3737If keys are integers, we can use an array.
3838
39- Store items in array indexed by key (draw picture) use None to
39+ Store items in array indexed by key (draw picture) use null to
4040indicate absense of key.
4141
4242What's good?
@@ -85,10 +85,23 @@ The word "hash" is from cooking: "a finely chopped mixture".
8585
8686## Chaining fixes collisions.
8787
88- * each slot of the hashtable contains a linked list of the items that
89- collided (had the same hash value)
90- * draw picture
91- * worst case: search in O(n)
88+ Each slot of the hashtable contains a linked list of the items that
89+ collided (had the same hash value).
90+
91+ Suppose we insert these key-value pairs:
92+
93+ (2, "sue"), (3, "larry"), (6, "joe"), (8, "beth")
94+
95+ Into a table of size 4, using mod for the hash function.
96+
97+ hash(key) = key % 4
98+
99+ 0| -> (8, "beth")
100+ 1|
101+ 2| -> (2, "sue") -> (6, "joe)
102+ 3| -> (3, "larry")
103+
104+ Worst case: search in O(n)
92105
93106Towards proving that the average case time is O(1).
94107
@@ -111,6 +124,18 @@ Towards proving that the average case time is O(1).
111124
112125Takeaway: need to grow table size m as n increases so that λ stays small.
113126
127+ ## Rehashing
128+
129+ When the load factor gets too high, we need to grow the table.
130+
131+ 1 . Allocate a new table that is double the size.
132+
133+ 2 . Insert all of the entries from the old table into the new table,
134+ using the new table size (the ` m ` ) in the hash function.
135+
136+ Rehashing is an O(n) operation, but by doubling the same of the table,
137+ it doesn't need to happen very often.
138+
114139## hash functions
115140
116141### division method: h(k) = k mod m
@@ -150,14 +175,28 @@ keys 4, 1, 3, 2, 0 into a hash table with table size 3 (m=3).
150175[ solution] ( ./Sep-25-solutions.md#student-exercise-1 )
151176
152177
153- ## Rehashing
178+ ## HashTable Lab Introduction
154179
155- When the load factor gets too high, we need to grow the table.
180+ ```
181+ public class HashTable<K,V> implements Map<K,V> {
156182
157- 1 . Allocate a new table that is double the size.
183+ class Entry {
184+ Entry(K k, V v) { key = k; value = v; }
185+ K key; V value;
186+ };
158187
159- 2 . Insert all of the entries from the old table into the new table,
160- using the new table size (the ` m ` ) in the hash function.
188+ protected ArrayList<LinkedList<Entry>> table;
161189
162- Rehashing is an O(n) operation, but by doubling the same of the table,
163- it doesn't need to happen very often.
190+ protected int hash(K key) { ... }
191+
192+ public HashTable(int table_size) { ... }
193+
194+ public boolean containsKey(K key) { ... }
195+
196+ public V get(K key) throws Exception { ... }
197+
198+ public void put(K key, V value) { ... }
199+
200+ public void remove(K key) { ... }
201+ }
202+ ```
0 commit comments