Presentation is loading. Please wait.

Presentation is loading. Please wait.

Heapify (Max Heap) Heap Sort Analysis

Similar presentations


Presentation on theme: "Heapify (Max Heap) Heap Sort Analysis"— Presentation transcript:

1 Heapify (Max Heap) Heap Sort Analysis
4/8/2019 CS 303 – Heap Sort Lecture 17

2 Heapify (Max Heap) Heapify(Root,Last) t  A[Root]; r  Root Repeat
s  r + r if s < Last if A[s] < A[s+1] s  s+1 if s <= Last if t < A[s] { A[r]  A[s]; r  s} Until r < s A[r]  t Heapify repairs a MaxHeap which has a suspect value at the root 4/8/2019 CS 303 – Heap Sort Lecture 17

3 HeapSort HeapSort(n) for i  n/2 downto 2 Heapify(i,n)
{ Heapify(1,i) /* A[1] is the MAXIMUM */ SWAP(1,i) /* move it to the output */ } Notice the similarity with: PriorityQueueSort(n) for i  1 to n Insert(A[i]) for i  1 to n DeleteMin(A[i]) except that HeapSort does it all in place (no extra space!) 4/8/2019 CS 303 – Heap Sort Lecture 17

4 Analysis First, a MaxHeap is built, from the leave up (demonstrate)
data changes from input  MaxHeap Next, the Maximum value is moved to the end of the array and then (here’s the trick!) that position in the array is removed from the MaxHeap and considered output! data changes from MaxHeap  output The second step is clearly(?) O(n log n) The first step is O(n) [exercise: prove it!] HeapSort is O(n log n) – the best we can do using Comparisons 4/8/2019 CS 303 – Heap Sort Lecture 17


Download ppt "Heapify (Max Heap) Heap Sort Analysis"

Similar presentations


Ads by Google