大家好,第一次来这里,但我想首先问一下我对双散列的理解是否正确。
双散列首先实现一个散列函数,然后检查该点是否打开。如果当前点未打开,则使用第二个散列函数确定另一个点,然后将其乘以当前尝试,然后将其添加到由第一个散列算法确定的索引点。
我现在的代码是:
unsigned int findPos(hashedObj& x)
{
int offset = 1;
int iteration = 0;
unsigned int originalPos = myhash1( x );
unsigned int index = originalPos;
unsigned int secondPos = myhash2( x );
while( array[ index ].info != EMPTY && array[ index ].element != x )
{
iteration = offset++ * secondPos;
if ( ( originalPos + iteration ) > array.size( ) )
index = ( originalPos + iteration ) % array.size( );
else
index = originalPos + iteration;
}
return ( index );
}
unsigned int hash1( const string& key, const int Tsize )
{
//start the hashvalue at 0
unsigned int hashVal = 0;
//cout<<" the size of the table is: "<< Tsize <<endl;
//add the ascii value for every word to hashval, multiply by 37 each time
for ( int i = 0; i < key.length(); i++ )
hashVal = 37 * hashVal + key[ i ];
//mod hashval so it remains smaller than the table size
hashVal %= Tsize;
//return the itemes index value
return hashVal;
}
我刚刚意识到我没有包含我的第二个哈希函数
unsigned int hash2( const string& key, const int Tsize )
{
//store the sum of ascii numerical values
int hashVal = 0;
//add the values of all chars while multiplying each one with a prime number
for ( int i = 0; i < key.length(); i++ )
hashVal = 29 * hashVal + key[ i ];
//mod the hashed value with a prime smaller than the table size, subtract that number
//with the prime just used and return that value
unsigned int index = 44497 - ( hashVal % 44497 );
return index;
}
它可能看起来不像,但实际上 tsize 被正确调用。