Priority Queue - Question 4 Answer

4

\begin{algorithm}
\caption{Heap Reprioritize}
\begin{algorithmic}
\REQUIRE heap = heap data structure
\REQUIRE index = index of the node to relocated in the heap
\FUNCTION{reprioritize}{heap, index}
    \STATE \COMMENT{It is assumed that the consumer updated a priority value and now needs to rearrange the heap}
    \IF{index = 0}
        \STATE \CALL{bubbleDown}{heap, 0}
        \RETURN
    \ENDIF
    \STATE parentIndex $\gets$ \CALL{parentIndex}{index}
    \STATE priority $\gets$ \CALL{heap.priorityFunc}{heap.data[index], heap.data[parentIndex]}
    \STATE
    \IF{priority = 0}
        \RETURN
    \ELSEIF{priority $\gt$ 0}
        \STATE \CALL{bubbleUp}{heap, index}
    \ELSE
        \STATE \CALL{bubbleDown}{heap, index}
    \ENDIF
\ENDFUNCTION
\end{algorithmic}
\end{algorithm}

Return to Exercises