平方探测的另一种插入方式

xiaoxiao2021-02-28  105

如果把新元素插入到搜索路径的第一个inactive单元,这样能够回收一个deleted单元,潜在的节省了空间。

查找元素位置时分两种情况,一种是元素已经在表中,则返回元素的位置。另一种是元素不在表中,则返回第一个inactive单元位置。添加新的变量firstPos记录第一个inactive单元位置。

findPos代码如下

int findPos(const HashedObj& x)const { int offset=1; int currentPos=myhash(x); int firstPos=currentPos; //循环结束时,firstPos为第一个inactive值或者active(值为x) while(array[firstPos].info==ACTIVE&&array[firstPos].element!=x) { firstPos+=offset; offset+=2; if(firstPos>=array.size()) firstPos-=array.size(); } currentPos=firstPos; //循环结束时currentPos的状态为empty或者deleted(值为x)或者active(值为x) while(array[currentPos].info!=EMPTY &&array[currentPos].element!=x) { currentPos+=offset; offset+=2; if(currentPos>=array.size()) { currentPos-=array.size(); } } //找到active(值为x)时,返回currentPos,否则返回第一个inactive位置 if(array[currentPos].info==ACTIVE) return currentPos; else return firstPos; }
转载请注明原文地址: https://www.6miu.com/read-60885.html

最新回复(0)