Heapsort Running Time Build-Heap(A
Total Page:16
File Type:pdf, Size:1020Kb
Heapsort Heap of n elements has height (show) - sorts in place – worst case running time All operations run in time proportional to the height - special data structure heap – complete binary tree Extract-Max, Insert, Extract-Min, Delete (completely filled except the lowest level) - Useful for priority queues Heap property : value of the node is at most - Discrete event simulators value of the parent A[Parent(i)] >= A[i] Algorithms for Heapify how to manipulate heaps Height of the node – number of edges on the longest path Buildheap how to build a heap from leaf to that node Heapsort how to sort using heap Idea: Implicit data structure – heap is represented by an Extract_max, array two attributes Insert maintain heap property is length(A) – length of the array heapsize(A) – number of elements of the heap Heap-Extract-Max(A) Remove A[1] How to get back and forth in the heap A[1] <- A[n] N <- n –1 Heapify(A,1,n) Different from the book Heapify(A,i,n) % assumes that L and R subtrees are heaps Build-Heap(A,n) % makes i’s subtree a heap if 2i · n and A[2i] > A[i] % build heap from unsorted array then largest <- 2i For i = n downto 1 else largest <- i do Heapify(A,i,n) if 2i+1 · n and A[2i+1] > A[largest] then largest <= 2i + 1 Simple bound on running time ≠ if largest i In fact more tight bound then exchange A[I] <-> A[largest] Heapify(A,largest,n) (idea of amortized analysis – more in chapter 18) Running time 1 Decision Tree Model Heapsort(A,n) Build-Heap(A,n) How to make sorting more efficient ? for i Å n downto 2 do exchange A[1] ÅÆ A[i] Can we do better then ? how to beat it ? Heapify(A,1,i-1) • establish the lower bound using the decision tree model Until now – sorting using comparisons only We for sure have to do at least comparisons to Variations – heap can be min (max) heap See all the input – can we provide tighter lower bound ? - heap can be k-ary tree instead of binary tree Decision Tree model – abstraction of comparison sorts Data Structures for dynamic sets – need to support -different algorithms follow different path in the decision tree efficiently basic operations (insert, delete, minimum, search) - there are at least n! leaves e.g. priority queues - decision tree for sorting n-elements has height - any sorting algorithm using comparisons takes at least on the order of n lg n operations 2.