问题已解决(尚不能接受答案,我更改了我的 while 循环,现在它可以工作了,我在下面为任何未来的观众回答了它):我的散列算法让我头疼。我从文件中读取键的输入,并且使用少量键,我的代码就可以工作,一旦我把它写成 300 个字,我就有问题了。散列函数在底部,而这个 while 循环在我的 main 函数的主体中,它是用 java 编写的。散列函数运行良好,主体也运行良好,直到我愚蠢地更改了主体并丢失了原始代码。我想我涵盖了溢出问题,但任何帮助将不胜感激,谢谢!
如何计算 tSize:
//Calcking tSize
tSize = (int)(items*tSizeFactor);
//Making tSize prime
while(!isPrime((int)tSize))
tSize++;
当我从文件中读取时循环:
while(line != null) {
//Getting the address to place the value in
position = hash(line.toCharArray(), (int)tSize);
//If there is something there we enter the if statement
if(hashTable[position][0] != null) {
//while we haven't found a spot and i < tableSize we update the last position we were at and move through the array
for(int i = 1; i < (int)tSize && hashTable[position][0] != null; i++) {
//prevPosition is used to update the link in the spot just before our final destination, allows wrap around in the array
prevPosition = position;
//we add +i to the original position and modulo the table size allowing wrap around in the array
position = (position+i)%(int)tSize;
}
//finally when we found a spot we update the previous position to link to the new item
hashTable[prevPosition][1] = Integer.toString(position);
}
//Adding the values to the hash table and setting the link to -1
hashTable[position][0] = new String(line);
hashTable[position][1] = new String(Integer.toString(-1));
line = reader.readLine();
}
public static int hash(char ch[],final int TSIZE) {
int sum = 7;
for(int i = 0; i < ch.length; i++) {
sum = sum*31+ch[i];
sum <<= 3;
}
if(sum < 0)
sum *= -1;
return sum%TSIZE;
}