Lecture13 - Applications of Heaps EECS 233-2- Application...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Applications of Heaps EECS 233-2- Application #1: Heap-sort Sorting algorithms: given an arbitrary array, re-position the items in the array in ascending or descending order A nave algorithm (we will learn more later) It isn t efFcient ( O (n 2 )), because it performs a linear scan to Fnd the smallest remaining item ( O (n) steps per scan). 4 6 11 9 15 5 7 16 13 15 6 11 9 4 5 7 16 13 15 6 11 9 4 7 5 16 13 15 13 11 9 4 7 5 16 6-3- Heap-Sort Heap-sort is a sorting algorithm that repeatedly fnds the largest remaining item From a heap and puts it in place. void heapSort(T arr, int length, int numItems) { // Turn the array into a max-at-top heap. Heap<T> heap = new Heap<T>(arr, length, numItems); int endUnsorted = numItems - 1; while (endUnsorted > 0) { // Get the largest remaining item and put it to the end T largestRemaining = heap.remove(); arr[endUnsorted] = largestRemaining; endUnsorted--; } } It is eFfcient ( O (N log N)): O(N) to turn the array into a heap O(log N) to remove the largest remaining item N above removals-4-...
View Full Document

Page1 / 13

Lecture13 - Applications of Heaps EECS 233-2- Application...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online