Quadratic probing doesn't hit all elements in prime numbered hash table
说我有一个包含59个元素的哈希表(每个元素值是一个整数)。索引15为空,表的其余部分充满了数据。根据我要插入的数字,二次探测公式永远不会命中元素15!
假设我想插入数字199(应该使用下面使用的hashFunc()函数将其哈希为22。:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public int hashFunc(int key) { return key % arraySize; //199 % 59 = 22 } public void insert(DataItem item) { int key = item.getKey(); // extract the key (199) int hashVal = hashFunc(key); // hash the key (22) int i = 1; //The while loop just checks that the array index isn't null and isn't equal to -1 which I defined to be a deleted element while(hashArray[hashVal] != null && hashArray[hashVal].getKey() != -1) { hashVal = hashFunc(key) + (i * i); //This never hits element 15!!! i++; hashVal %= arraySize; // wraparound when hashVal is beyond 59 } hashArray[hashVal] = item; // insert item } |
这在二次探测哈希表中是期望的。使用一些模块化算法,您可以证明只能保证探针序列中的前p / 2个探针位置是唯一的,这意味着每个元素的探针序列有可能不会访问探针中一半的位置。表。
要解决此问题,您可能应该更新代码,以便在使用p / 2或更多表位置时重新哈希。或者,您可以使用Wikipedia文章上建议的技巧,交替改变探针偏移量的符号(1,-4、9,-16、25等),这应确保您可以击中每个可能的位置。 >
希望这会有所帮助!