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?

  1. A. for (i = k % m; t[i] != EMPTY; i++) if (t[i] == k) return i; return -1;
  2. B. for (i = k % m; ; i++) if (t[i] == k) return i;
  3. 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;
  4. 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

Exams that ask this topic