algorithm - Trying to understand max heapify -
i tried watching http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-4-heaps-and-heap-sort/ understand heaps , heapsort did not find clear.
i not understand function of max-heapify. seems recursive function, somehow it's said run in logarithmic time because of height of tree.
to me makes no sense. in worst case, won't have reverse every single node? don't see how can done without touching every single node, repeatedly.
here's max-heapify does:
given node @ index i left , right subtrees max-heaps, max-heapify moves node @ i down max-heap until no longer violates max-heap property (that is, node not smaller children).
the longest path node can take before in proper position equal starting height of node. each time node needs go down 1 more level in tree, algorithm choose 1 branch take , never backtrack. if node being heapified root of max-heap, longest path can take height of tree, or o(log n).
max-heapify moves 1 node. if want convert array max-heap, have ensure of subtrees max-heaps before moving on root. calling max-heapify on n/2 nodes (leaves satisfy max-heap property).
from clrs:
for = floor(length(a)/2) downto 1 max-heapify(a,i) since call max-heapify o(n) times, building entire heap o(n log n).
Comments
Post a Comment