首页 > 解决方案 > 如何让我的线性探测散列函数更高效?

问题描述

我在这里努力查看我的线性探测技术是否正确以及它是否有效。我有什么办法可以提高效率吗?

static void enterValues(int values[], int hashTable[])
{
    for(int i = 0; i < values.length; i++){
        int k = hashFunction(values[i]);
        if(hashTable[k]== 0)
        hashTable[k] = values[i];
        else{
            boolean b = false;
            int counter = k%hashTable.length+1;
            if(counter >= hashTable.length)
                counter = 0;
                while (!b) {
                    if (hashTable[counter] == 0) {
                        hashTable[counter] = values[i];
                        b = true;
                    } else {
                        counter = counter % hashTable.length+1;
                    }
                }
            }
        }
    }

static int hashFunction(int value)
{
    return value % 10;
}

int values[] = {4371,1323,6173,4199,4344,9679,1989};

大小为 10 的哈希集的输出是

9679,
4371,
1989,
1323,
6173,
4344,
0,
0,
0,
4199

谢谢你看

标签: javaalgorithmhash

解决方案


It is incorrect. Consider what happens if value[i] is zero:

   if (hashTable[k] == 0) {
        hashTable[k] = values[i];
   } else { .... }

Since you are using zero in the hashtable to mean that the entry is not used, and you are also assigning values directly into the table, your code cannot distinguish a zero value from an empty entry.


推荐阅读