我的代码卡在哈希搜索方法的第二个 while 循环中。似乎条件保持真实,如果密钥不在数据集中或找到密钥,它们最终应该变为错误。有人可以帮我找到错误吗?
谢谢
////// 这是全部..我一直在努力..仍然找不到错误。
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
Initialize();
int SearchKey;
int TotalNumberOfComparisons;
int address;
int M;
M = FindPrime();
for(int i=0; i<NumberOfDataItems; i++)
{
address = OriginalArray[i] % M;
if (HashedArray[address]== -1)
HashedArray[address]= OriginalArray[i];
else
{
address = (address+1) % M;
while(HashedArray[address]!=-1)
{
address=(address+1)%M;
}
HashedArray[address]=OriginalArray[i];
}
}
System.out.println("after mapping" + M);
long startTime = System.nanoTime();
boolean found = false;
for (int k = 0; k <NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
address = KeysArray[k] % M;
//System.out.println("address" + address);
//System.out.println(" inside if 1 --- address" + address);
while ( HashedArray[address]!= SearchKey && HashedArray[address]!= -1)
{
if (HashedArray [address] == SearchKey)
{
found = true;
TotalNumberOfComparisons++;
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
System.out.println("Stuck after here");
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
//address=(address+1)%M;
address++;
}
System.out.println(" outside while --- found" + found);
//if(HashedArray[address] == SearchKey)
//found = true;
//else found = false;
//address=(address+1)%M;
//address++;
}
if(found)
{
HSAverageCompSuc = HSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
HSAverageCompFailed = HSAverageCompFailed + TotalNumberOfComparisons;
HSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
HSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
HSAverageAccessTime = 0;
if(HSNumberKeysSuc != 0)
HSAverageCompSuc = Math.round (HSAverageCompSuc / HSNumberKeysSuc) ;
else
HSAverageCompSuc = 0;
if (HSNumberKeysFailed != 0)
HSAverageCompFailed = Math.round (HSAverageCompFailed / HSNumberKeysFailed) ;
else
HSNumberKeysFailed = 0;
System.out.println("time after search" + estimatedTime);
return;
}