【问题标题】:Java: Need help on hashing function overflowJava:在散列函数溢出方面需要帮助
【发布时间】:2012-11-02 21:17:39
【问题描述】:

我正在处理一项任务,我必须将 10,000 个数字散列到负载大小为 0.1、.2 .3 .... 到 0.9 的散列表中。我的问题是我的散列函数给了我一些溢出或类似的东西。如果我对负载因子为 0.5 的表(如 36077(mod)20,000)进行哈希处理,它会给我 16070 作为键。这只发生在高于负载因子的数字上。这是我的散列函数的代码。

    public int linearHash(int in){
    int hashKey = in%hashTableArray.length;
    while(this.hashTableArray[hashKey] != 0){
        hashKey += 1;
    }
    return hashKey;
}

谢谢。

【问题讨论】:

  • 正如@Reimeus 下面所说的,对于开放寻址hashKey,如果它到达数组的末尾,它应该回绕为零。如果数组已满,请注意不要进入无限循环。

标签: java hash hashtable integer-hashing


【解决方案1】:

您没有在while 循环中检查是否超出了hashTableArray 的索引范围。你可以这样做:

while (hashKey < hashTableArray.length && this.hashTableArray[hashKey] != 0){

【讨论】:

    【解决方案2】:

    Reimeus 指出了OutOfBound 问题并给出了解决方案。我只是想补充一些关于你处理碰撞的方式。

    你的函数看起来像开放寻址方法。而不是hashKey += 1; 也许你可以考虑增加in

     public int linearHash(int in){   
        int hashKey = in%hashTableArray.length;
        while(this.hashTableArray[hashKey] != 0){
            in ++;
            hashKey = in%hashTableArray.length;
        }
        return hashKey;
    }
    

    上面的示例代码没有检查哈希表溢出。自动增量不应超过hashTableArray.length 次。否则你的程序会陷入死循环

    请注意,通过检查hashTableArray[hashKey] != 0 来确定插槽是否空闲是不安全的。例如,您的元素中有数字020000 怎么样?

    【讨论】:

      猜你喜欢
      • 2011-02-14
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2014-02-06
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多