Why does incrementing offset by 2 make sense? I know this algorithm works, I have plotted the results resulting in a x^2 type graph but I just can't see it. Could someone explain it in simple terms? Thank you!
size_t FindPos(const HashedObj & x) const {
size_t offset = 1;
size_t current_pos = InternalHash(x);
while (array_[current_pos].info_ != EMPTY && array_[current_pos].element_ != x) {
current_pos += offset;
offset += 2;
if (current_pos >= array_.size())
current_pos -= array_.size();
}
return current_pos;
}
You are increasing
offsetby2in every iteration, so after then-th iteration if will have value1+2*n.You are adding this to
current_posin each iteration. So in the first iteration you are adding1+0*2tocurrent_pos, in the second you are adding1+1*2, in the third1+2*2and so on.The total amount added to
current_posby the end of them'th iteration of the body will therefore be the sum of1+2*nfromn=0ton=m-1, neglecting the modulo operation for a moment.Using linearity of addition, this sum can be written as
m + 2 * sum(n for n=0 to m-1). The remaining sum can be shown to evaluate tom*(m-1)/2, so that the total isSo this method does the same as using
(current_pos + m**2) % array_.size()in each iteration withmbeing the loop counter and without modifyingcurrent_poswould.