Why not just add one in the secondary hash function after mod?

Viewed 12

When working with a hash table with double hashing, the secondary hash function may be something like 7 - (key % 7). It is said that the reason for not using key % 7 directly is to avoid the secondary hash function ever returning 0, such that the algorithm does not keep looping on itself with every step.

Instead of having key % 7:

  • Key 0: 0 % 7 = 0
  • Key 1: 1 % 1 = 1
  • ...
  • Key 6: 6 % 7 = 6
  • Key 7: 7 % 7 = 0
  • Key 8: 8 % 7 = 1
  • ...

We have 7 - (key % 7):

  • Key 0: 7 - (0 % 7) = 7
  • Key 1: 7 - (1 % 1) = 6
  • ...
  • Key 6: 7 - (6 % 7) = 1
  • Key 7: 7 - (7 % 7) = 7
  • Key 8: 7 - (8 % 7) = 6
  • ...

The sequence changes from a repeating range of 0-6, to a repeating range of 7-1. My question is, would it work similarly well to simply use (key % 7) + 1? It appears to achieve a similar range of repeating 1-7 while avoiding 0s.

0 Answers
Related