简体   繁体   中英

Heap code line explanation

if (index != indexMaxim)
{
    Rezervare aux = heap.vectorRezervari[index];
    heap.vectorRezervari[index] = heap.vectorRezervari[indexMaxim];
    heap.vectorRezervari[indexMaxim] = aux;

    if (indexMaxim < (heap.nrElements - 1) / 2) // I REALLY DONT GET WHAT THAT MEAN...
        filtrareHeap(heap, indexMaxim);
}

I'm working on a heap structure and I think that this line is to compare the value of indexMaxim to the Parent node so if the value is less than the filtrareHeap() method is called to interchange the indices.

Can you give me a more specific explanation?

In a zero-based array-hosted heap of size n , where n > 0 holds true, given any parent node index i such that i is in [0,n-1] , where n is the node count of the heap, the corresponding children nodes can be found at:

2 * i + 1
2 * (i + 1)

in such case where each of the above is likewise in [0,n-1]

Given that, one can determine the first node that genuinely has no possible children (and is therefore leaf nodes from that point on in the heap) by taking the heap size, subtracting one to account for the zero-based indexing model, then integer-dividing by two.

Given a heap of size 7, the equation yields 3. And that makes sense because, given indexes

0 1 2 3 4 5 6

we know that

  • 0 is parent of 1,2
  • 1 is parent of 3,4
  • 2 is parent of 5,6

Therefore, the first node that will have no children in the tree is 3. The condition you're questioning simply determines whether the node is less than that position, and if it is, take further action; otherwise stop.

The conditional you flag appears to be testing whether indexMaxim corresponds to an internal node of the heap, as opposed to a leaf node. If it is an internal node then the value may need to filter down farther, hence the (recursive?) call to filtrareHeap() , but if it is a leaf node then the value can't go any farther than that node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM