Note that there are some explanatory texts on larger screens.

plurals
  1. POhow would you ensure subscript element access is within the size limit of a heap container e.g vector in implementing a move_down_the_heap function?
    text
    copied!<p>the interface looks like this </p> <pre><code>template &lt;class T, class Pred&gt; void downheap (std::vector&lt;T&gt;&amp; heap_vector, unsigned int startingIndex, Pred predicateFunc); </code></pre> <p>if the <em>startingIndex</em> is at <strong>k</strong> in the vector, its <strong>left child</strong> in the heap will be located at index <strong>(2 * k)</strong> and its <strong>right child</strong> in the heap will be located at index <strong>((2 * k )+ 1)</strong>. essentially, the item should be compared (and swapped as necessary) with its appropriate child in the heap until the given order by the predicate function has been satisfied.</p> <p>the predicate might be greaterthan, lesserthan or any custom sequence...</p> <p>in implementing such a method, how do you check that index access is within the size limit? i.e <strong>heap_vector[rightChildIndex]</strong> or <strong>heap_vector[leftChildIndex]</strong> should not go beyond <strong>heap_vector.size()-1</strong> while looping and doing comparison... it has given me a bit of a headache</p> <p>here is my code </p> <pre><code> while ( pred ( heap_vector[rightChild], heap_vector[parentIndex] ) || pred ( heap_vector[leftChild], heap_vector[parentIndex] ) ) { if ( pred ( heap_vector[rightChild], heap_vector[leftChild]) ) { std::swap(heap_vector[parentIndex],heap_vector[rightChild]); parentIndex=rightChild; } else { std::swap( heap_vector[parentIndex], heap_vector[leftChild]); parentIndex=leftChild; } rightChild= 2*parentIndex+1; leftChild=2*parentIndex; if (rightChild&gt;heap_vector.size() || leftChild&gt;heap_vector.size()) break; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload