Question

I am working on an assignment were I have to hash 10,000 numbers into a hash table of load size .1, .2 .3 .... up to .9. My problem is that my hashing function is giving me some overflow or something of the sort. If am doing a hash for a table with load factor of .5 like 36077(mod)20,000 it gives me 16070 as the key. This only happens on numbers that are above the load factor. This is the code for my hashing function.

    public int linearHash(int in){
    int hashKey = in%hashTableArray.length;
    while(this.hashTableArray[hashKey] != 0){
        hashKey += 1;
    }
    return hashKey;
}

Thank you.

Was it helpful?

Solution

You are not checking that you are exceeding the index bounds of the hashTableArray in your while loop. You could do:

while (hashKey < hashTableArray.length && this.hashTableArray[hashKey] != 0){

OTHER TIPS

Reimeus pointed out the OutOfBound problem and gave a solution. I just want to add something about your way to handle collision.

Your function looks like open addressing approach. instead of hashKey += 1; perhaps you could consider to increment the in

 public int linearHash(int in){   
    int hashKey = in%hashTableArray.length;
    while(this.hashTableArray[hashKey] != 0){
        in ++;
        hashKey = in%hashTableArray.length;
    }
    return hashKey;
}

the example codes above didn't check for hashtable overflow. the auto-increment should not happen more than hashTableArray.length times. otherwise your program falls into dead loop

and please note that decide if a slot is free by checking hashTableArray[hashKey] != 0 is not safe. for example, what about there are number 0 and 20000 in your elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top