Имам някои проблеми с кода за percolate нагоре и надолу в min-heap (най-малкият ключ отгоре). Най-голямото ми недоволство е с 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 ] );
Не разбирам for цикъла тук. Може да е свързано с връзките, като че родителят на i-тия индекс е в i/2 и т.н., но не съм наясно с това. Това е за вмъкване на елемент в купчината. Оценява се всяка помощ при излагането на значението на кода.
След това има percolate down за метода 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...
Основно for цикъла, но също и коя част от кода какво прави? Извинявам се ако има аматьорство във въпроса.