lecture-16

# More efciently notice in the simple approach we use a

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ­ ­ Fall 2010 6 2 5 9 Heapsort •  Building the Heap more efﬁciently // building the heap for(int i = (size ­1)/2; i &gt;= 0; i ­ ­) HeapRebuild(array, size, i); CPSC 223  ­ ­ Fall 2010 10 5 10/26/10 Heapsort •  Sorting from the Heap more efﬁciently –  Notice in the simple approach we use a temporary array –  We can avoid this by performing heapsort “in place” –  After each deletion, maintain two partitions of the array: •  The sorted region (the end of the array) •  The Heap region (the beginning of the array Heap array = Sorted … 0 1 2 … last last+1 n ­1 CPSC 223  ­ ­ Fall 2010 11 Array-Based Heap Implementation void heapRebuild(int theArray, int size, int index) { int child = 2*index + 1; if(child &lt; size) { int right = child + 1; if(right &lt; size &amp;&amp; theArray[right] &gt; theArray[child]) child = right; if(theArray[index] &lt; theArray[child]) { swap(theArray[index], theArray[child]); heapRebuild(theArray, size, child); } } } CPSC 223  ­ ­ Fall 2010 12 6 10/26/10 Heapsort void heapsort(int theArray, int size) { for(int i = (size-1)/2; i &gt;= 0; i--) heapRebuild(theArray, size, i); // build int last = size-1; for(int j = 1; j &lt; size; j++) { swap(theArray[0], theArray[last]); heapRebuild(theArray, last, 0); last--; } // delete } CPSC 223  ­ ­ Fall 2010 13 Comparison of Sorting Algorithms Best Case Average Case Worst Case SelecSon Sort O(n2) O(n2) O(n2) Bubble Sort O(n) O(n2) O(n2) InserSon Sort O(n) O(n2) O(n2) Mergesort O(nlogn) O(nlogn) O(nlogn) Quicksort O(nlogn) O(nlogn) O(n2) Treesort O(nlogn) O(nlogn) O(n2) Heapsort O(nlogn) O(nlogn) O(nlogn) CPSC 223  ­ ­ Fall 2010 14 7...
View Full Document

## This document was uploaded on 03/18/2014 for the course CPSC 223 at Gonzaga.

Ask a homework question - tutors are online