将密钥插入长度为9的哈希表中

时间:2016-06-04 06:48:59

标签: data-structures hashtable hash-function mod

所以,我正在解决一个需要我在哈希表中按顺序插入密钥的问题。因为没有更多的空间,我在20后停止插入。我提供以下图片来帮助上下文。我创建了哈希表,找到了冲突次数和加载因子。通过开放寻址解决冲突。对不起,这不是问题,我只需要有人查看它并告诉我它是否正确。 My finished work

1 个答案:

答案 0 :(得分:2)

您的问题中存在许多错误和误解。

  • 你声明你在20岁以后停止了插入。但你显示15个键。
  • 您的哈希表中有9个桶,但是您说明加载因子是1.加载因子是键数(15或20)除以桶数(9)所以它不是1. / LI>
  • 在哈希函数中h(k,i) k是密钥,i是桶的数量。在你的情况下i是9,所以函数(k mod 9 + 5i) mod 9真的没有意义。
  • 所有哈希函数都应以mod i结尾。
  • 您提供的按键中没有15次碰撞。仅当表中存在先前值时才会发生冲突。

这一点在维基百科关于hashtables的文章中有所解释。

在下面的评论中澄清了这个答案时,我使用以下代码来验证您的结论:

public class Hashing {
    private static final int SIZE = 9;
    private final int[] keys = new int[SIZE];
    private int collisions = 0;

    public void add(int key) {
        int attempt = 0;
        while (keys[hash(key, attempt)] > 0)
            attempt++;
        collisions += attempt;
        keys[hash(key, attempt)] = key;
    }

    private int hash(int key, int attempt) {
        return (key % SIZE + 5 * attempt) % SIZE;
    }

    public static void main(String[] args) {
        Hashing table = new Hashing();
        Stream.of(28, 5, 15, 19, 10, 17, 33, 12, 20).forEach(table::add);
        System.out.println("Table " + Arrays.toString(table.keys));
        System.out.println("Collisions " + table.collisions);
    }   
}

并收到以下输出:

Table [20, 28, 19, 33, 12, 5, 15, 10, 17]
Collisions 15
相关问题