C++ 了解堆(优先级队列)中的渗流上下函数

C++ 了解堆(优先级队列)中的渗流上下函数,c++,algorithm,data-structures,heap,C++,Algorithm,Data Structures,Heap,我在min堆(顶部最小的键)中上下渗透的代码中遇到了一些问题。我最大的不满是这两个代码段的for循环,这导致我无法理解其余的代码 int hole = ++currentSize; Comparable copy = x; array[ 0 ] = std::move( copy ); //in the books implementation the zero //index is kept empty, is this to create a temporary place for th

我在min堆(顶部最小的键)中上下渗透的代码中遇到了一些问题。我最大的不满是这两个代码段的for循环,这导致我无法理解其余的代码

int hole = ++currentSize;
Comparable copy = x;

array[ 0 ] = std::move( copy ); //in the books implementation the zero 
//index is kept empty, is this to create a temporary place for the added element?
for( ; x < array[ hole / 2 ]; hole /= 2 ) //my biggest problem is understanding this for loop!!!
    array[ hole ] = std::move( array[ hole / 2 ] ); //what does this do?
array[ hole ] = std::move( array[ 0 ] );
int-hole=++currentSize;
可比拷贝=x;
数组[0]=std::move(复制)//在书中实现了零
//索引保持为空,这是为添加的元素创建临时位置吗?
for(;x
我不明白这里的for循环。这可能与关系有关,比如i'th索引的父级在i/2中等等,但我对此一无所知。这是向堆中插入一个元素。我们非常感谢您在阐述本规范含义时提供的任何帮助

然后是findMin方法的渗滤液,我同样不理解它的代码

/**
    * Internal method to percolate down in the heap.
    * hole is the index at which the percolate begins.
    */
void percolateDown( int hole )
{
    int child;
    Comparable tmp = std::move( array[ hole ] );

    for( ; hole * 2 <= currentSize; hole = child ) //not clear with this for loop!!!
{
    child = hole * 2;
    if( child != currentSize && array[ child + 1 ] < array[ child ] )
    ++child;
    if( array[ child ] < tmp )
    array[ hole ] = std::move( array[ child ] );
    else
        break;
    }
    array[ hole ] = std::move( tmp );
    } //somewhat understood, except the for loop...
/**
*在堆中向下渗透的内部方法。
*孔是渗滤液开始的指数。
*/
孔隙向下渗透(内部孔)
{
智力儿童;
可比tmp=标准::移动(阵列[孔]);

for(;hole*2正如您所说:元素
i
的父元素位于
i/2
。代码所做的是插入一个“hole”,这将是放置新元素的位置。for循环中的行:

array[hole]=std::move(array[hole/2]);

将父对象移动到子对象的位置(即“洞”)。因此,我们基本上做的是

while (element being moved up < parent)
    move parent to current index
    current index = index of parent
place element at current index
while(元素上移<父元素)
将父项移动到当前索引
当前索引=父项的索引
将元素放置在当前索引中
另一段代码正好相反。它有点复杂,因为每个元素只有一个父元素,它可能有两个子元素。第一个位于
i*2
,第二个位于
i*2+1
。首先我们检查元素是否有子元素(
child!=currentSize
)。我们只想在子项较小时将父项与子项交换。因此,我们查看哪个子项最小(
array[child+1]
)。我们将该子项与其父项进行比较:如果子项较小,我们交换它们并继续,否则我们就完成了。最后,我们将要移回的元素放在“孔”中