ProgrammingVery hard
Which search code is correct for an open-addressing table of size m with linear probing, where an empty slot ends the search?
- A. for (i = k % m; t[i] != EMPTY; i++) if (t[i] == k) return i; return -1;
- B. for (i = k % m; ; i++) if (t[i] == k) return i;
- C. for (i = k % m, c = 0; c < m && t[i] != EMPTY; c++, i = (i + 1) % m) if (t[i] == k) return i; return -1;
- D. for (i = 0; i < m; i++) if (t[i] == k) return i; return k % m;
Correct answer: C. for (i = k % m, c = 0; c < m && t[i] != EMPTY; c++, i = (i + 1) % m) if (t[i] == k) return i; return -1;
The loop wraps around with % m and is bounded by m, so it never reads past the array. The other versions run off the end or skip the wrap.
More C Programming questions
- A hash table stores pointers to nodes allocated with malloc. What must happen when the table is destroyed?
- The expected number of probes for an unsuccessful search in linear probing with load factor a = 0.9 is about what?
- For a hash map of N = 10^5 entries with 10^5 lookups, which implementation is correct and fast enough in C?
- A chained table has a load factor of 3. A successful search compares the key against nodes until it is found. What is the expected number…
- Keys are stored with h(k) = k % 10 in a chained table. Which key set gives the longest single chain for five keys?
- A table keeps keys as ints in an array of size 2^20 indexed directly by the key. Keys are at most 10^6. Which statement is correct?