Heap Sort - CIS@UAB

Download Report

Transcript Heap Sort - CIS@UAB

5/1/2020

Heap Sort

Heapify (Max Heap) Heap Sort Analysis CS 303 – Heap Sort Lecture 17 1

Heapify (Max Heap)

Heapify(Root,Last) t  A[Root]; r  Repeat Root 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  Until r < s A[r]  t s} Heapify repairs a MaxHeap which has a suspect value at the root 5/1/2020 CS 303 – Heap Sort Lecture 17 2

HeapSort

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

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 5/1/2020 CS 303 – Heap Sort Lecture 17 4