How does a code choose its starting bucket?

Choosing a home index

Elena Ruiz

How a hash table finds a value

When you divide 5 by 4, what's left is 5 − 4 = 1, so the home index is 1.

Transcript

The hash code slides into place above the buckets. It has to tell you which bucket to use, but none has that number.

The hash code is 5, so you need to turn it into a number you can find on this row. Look at the buckets numbered 0, 1, 2 and 3, and you'll see all 4 available choices. That count goes into the calculation as the number to divide by, so you divide 5 by 4. You're counting every bucket, even an empty one, because the capacity is the number of buckets the table has. With a capacity of 4, you take away whole groups of 4 and keep what's left.

Now count what's stored instead: there are just 2 entries, and that count is the table's size. Size tells you how much is stored, not how many places there are to put it. If you divided by 2 instead, your only available choices would be buckets 0 and 1. That's because 2 left over would already make another pair, so no code could ever land in bucket 2 or 3 that way.

So go back to all 4 buckets and use that count to make whole groups of 4. Just 1 group of 4 fits into 5, because 2 groups would take 8. So subtract the whole group that fits: 5 minus 4 leaves 1. What's left after you take away as many whole groups as fit without going below zero is the remainder. Here the remainder is the 1 you keep, not the group you took away.

Notice why the calculation always leaves less than 4: if there were any more than 3 left, you could take away another whole group. Now try the small codes, 0, 1, 2 or 3, and each leaves itself because no whole group of 4 fits. So those are all the possible leftovers, and they match the numbers on the buckets exactly.

Follow the result for hash code 5: the 1 left over goes straight to bucket 1 because the numbers match. That first bucket number the table chooses for your key is its home index. So dividing 5 by the bucket count leaves 1, and that makes 1 your home index.