12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Sec. 7.6 Heapsort 257<strong>and</strong> fast. The algorithm should take advantage of the fact that sorting is a specialpurposeapplication in that all of the values <strong>to</strong> be s<strong>to</strong>red are available at the start.This means that we do not necessarily need <strong>to</strong> insert one value at a time in<strong>to</strong> thetree structure.Heapsort is based on the heap data structure presented in Section 5.5. Heapsorthas all of the advantages just listed. The complete binary tree is balanced, its arrayrepresentation is space efficient, <strong>and</strong> we can load all values in<strong>to</strong> the tree at once,taking advantage of the efficient buildheap function. The asymp<strong>to</strong>tic performanceof Heapsort is Θ(n log n) in the best, average, <strong>and</strong> worst cases. It is not asfast as Quicksort in the average case (by a constant fac<strong>to</strong>r), but Heapsort has specialproperties that will make it particularly useful when sorting data sets <strong>to</strong>o large <strong>to</strong> fitin main memory, as discussed in Chapter 8.A sorting algorithm based on max-heaps is quite straightforward. First we usethe heap building algorithm of Section 5.5 <strong>to</strong> convert the array in<strong>to</strong> max-heap order.Then we repeatedly remove the maximum value from the heap, res<strong>to</strong>ring the heapproperty each time that we do so, until the heap is empty. Note that each time weremove the maximum element from the heap, it is placed at the end of the array.Assume the n elements are s<strong>to</strong>red in array positions 0 through n−1. After removingthe maximum value from the heap <strong>and</strong> readjusting, the maximum value will nowbe placed in position n − 1 of the array. The heap is now considered <strong>to</strong> be of sizen − 1. Removing the new maximum (root) value places the second largest valuein position n − 2 of the array. At the end of the process, the array will be properlysorted from least <strong>to</strong> greatest. This is why Heapsort uses a max-heap rather thana min-heap as might have been expected. Figure 7.10 illustrates Heapsort. Thecomplete Java implementation is as follows:static

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!