I've been stressing for a while now with this hash table yet I can't seem to find what is causing these infinite loops. Insertion usually stops at around half way point. Key consists of a string of 64 random symbols separated by an underscore in the middle. Need help trying to debug this!
Here are the Table constructor, both hash functions and the insertion method:
private int maxsize;
private int size;
private TableEntry[] table;
private int primeSize;
public HashTable(int ts)
{
size = 0;
maxsize = ts;
table = new TableEntry[maxsize];
for (int i = 0; i < maxsize; i++)
table[i] = null;
primeSize = getPrime();
}
public int getPrime()
{
for (int i = maxsize - 1; i >= 1; i--)
{
int fact = 0;
for (int j = 2; j <= (int)Math.Sqrt(i); j++)
if (i % j == 0)
fact++;
if (fact == 0)
return i;
}
return 3;
}
public void Insert(string key, double value)
{
if (size == maxsize)
{
Console.WriteLine("Table full");
return;
}
int hash1 = myhash1(key);
int hash2 = myhash2(key);
Console.WriteLine(" Hashed keys: {0}, {1}", hash1, hash2);
while (table[hash1] != null)
{
hash1 += hash2;
hash1 %= maxsize;
}
table[hash1] = new TableEntry(key, value);
size++;
}
private int myhash1(string key)
{
int hashVal = key.GetHashCode();
hashVal %= maxsize;
if (hashVal < 0)
hashVal += maxsize;
return hashVal;
}
private int myhash2(string key)
{
int hashVal = key.GetHashCode();
hashVal %= maxsize;
if (hashVal < 0)
hashVal += maxsize;
return primeSize - hashVal % primeSize;
}
The while
loop in Insert
could get into an infinite loop if it cycled back to the same index in the array without finding an empty spot. To prevent this problem, you could augment the double hashing strategy with a "just find the next available free space" strategy - switching to the second strategy if the first strategy failed. You would need another variable to keep track of the original value of hash1
to implement that.