Heap Sort by 1c05dw2

VIEWS: 9 PAGES: 4

									              Heap Sort


           Heapify (Max Heap)
               Heap Sort
                Analysis




6/7/2012     CS 303 – Heap Sort   1
                 Lecture 17
                      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




6/7/2012                   CS 303 – Heap Sort                     2
                               Lecture 17
                             HeapSort

HeapSort(n)
 for i  n/2 downto 2 Heapify(i,n)
 for i  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  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!)


6/7/2012                    CS 303 – Heap Sort                3
                                Lecture 17
                                 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

6/7/2012                       CS 303 – Heap Sort                    4
                                   Lecture 17

								
To top