开发者

Can't seem to break a while loop on collision, hashing

开发者 https://www.devze.com 2023-03-04 04:48 出处:网络
I don\'t know why this code is not breaking out of the while loop: int table_size = 953; store hash_table[953];

I don't know why this code is not breaking out of the while loop:

int table_size = 953;
store hash_table[953];
for(int i = 开发者_Go百科0; i < table_size; i++)
    hash_table[i].count = 0;

//bunch of stuff to get hash value here

while(hash_table[hashNum].data != pString || hash_table[hashNum].count != 0){
    hashNum++;
    if(hashNum > table_size)
        hashNum = 0;
    cout << hash_table[hashNum].count; 
    // to check the value of the count in the array, it IS 0, thus should have broken the loop
}


you probably mean:

while(hash_table[hashNum].data != pString && hash_table[hashNum].count != 0)

In your code the loop will continue if either case is true, hash_table[hashNum].count == 0 is NOT sufficient to make the clause false.


hash_table[hashNum].count being equal to zero is not sufficient to terminate the loop since you are using || ("or") between the two conditions in the termination test. If hash_table[hashNum].data is not equal to pString then the loop will continue regardless of what hash_table[hashNum].count is.


I think your loop condition should be on hashNum != 0 instead of hash_table[hashNum].count != 0.

Secondly, there should be && instead of || in your while condition.

These are wild guesses since a lot of information is missing in this question.


You should have a look at binary logic, especially De Morgan theorem

!(a && b) is equivalent to (!a) || (!b)
0

精彩评论

暂无评论...
验证码 换一张
取 消