Complete the code to calculate the hash index for a given key.
func hash(key int, size int) int {
return key [1] size
}The modulo operator (%) is used to ensure the hash index stays within the table size.
Complete the code to find the next index using linear probing.
func linearProbe(index int, size int) int {
return (index [1] 1) % size
}Adding 1 moves to the next slot in linear probing.
Fix the error in the insertion loop to avoid infinite loops.
for i := 0; i < size; i++ { idx := (hash(key, size) + i) [1] size if table[idx] == nil { table[idx] = &key break } }
The modulo operator (%) ensures the index wraps around the table size to avoid out-of-range errors and infinite loops.
Fill both blanks to complete the search function using linear probing.
func search(key int, table []*int, size int) int {
start := hash(key, size)
for i := 0; i < size; i++ {
idx := (start [1] i) [2] size
if table[idx] == nil {
return -1
}
if *table[idx] == key {
return idx
}
}
return -1
}We add i to the start index and use modulo (%) to wrap around the table during linear probing search.
Fill all three blanks to complete the delete function using linear probing.
func delete(key int, table []*int, size int) bool {
start := hash(key, size)
for i := 0; i < size; i++ {
idx := (start [1] i) [2] size
if table[idx] == nil {
return false
}
if *table[idx] == key {
table[idx] = [3]
return true
}
}
return false
}We add i to start and use modulo (%) to wrap index. Setting table[idx] to nil deletes the key.
