270 likes | 455 Views
Heapsort Algorithm. Eric & Bruce. Q: What is “Heapsort”?. It is a sorting algorithm which takes an array of values and sorts them in either descending order or ascending order. Q: How Fast is heapsort?. Heapsort is guaranteed to run in O(n log n) time. Avg Run time: O(n log n)
E N D
Heapsort Algorithm Eric & Bruce
Q: What is “Heapsort”? • It is a sorting algorithm which takes an array of values and sorts them in either descending order or ascending order.
Q: How Fast is heapsort? • Heapsort is guaranteed to run in O(n log n) time. • Avg Run time: O(n log n) • Worst Case run time: O(n log n) • Compare the Big O run time with Quicksort
Q: How does Heapsort compare? Part 1: Average Run time test results, by compiler and chipset Source: http://www.azillionmonkeys.com/qed/sort.html
Q: How does Heapsort compare? Part 2: Comparisons and Read/Writes Source: http://www.azillionmonkeys.com/qed/sort.html
Runtime Conclusions: • Quicksort is faster then Heapsort in the Average case. • Heapsort is faster then Quicksort when Quicksort hits its worst case scenario [O(n^2)] • Best Algorithm: Hybrid of Quicksort and Heapsort • Final Note: Use quicksort. The performance is slightly better then Heapsort.
Q: How does Heapsort work? • General Outline:Step 1: Get an unsorted arrayStep 2: “Heapify” the arrayStep 3: Pop off the root node of the heapStep 4: Adjust Heap to maintain its heapish propertiesStep 5: Pop off roots until none exist
Properties of a Heap • Each node has a left and right child • All the leaves are at the bottom level or the bottom 2 levels • Nodes are filled from left to right • All levels are completely filled with nodes (exception: bottom level) • Min-Heap: Each child node is greater then the parent node • Max-Heap: Each child node is less then the parent node
Heap as an Array Heap Array
Lets see some L33t code Parent(CI) = (CI - 1) / 2; RightChild(CI) = 2 * (CI + 1); LeftChild(CI) = 2 * CI + 1;
Inserting into a Heap • Insert “E”
Inserting into a Heap Start by filling “E” into the next available node This insertion may cause our tree to not be a heap anymore!!!
Inserting “D” into the heap Start by filling “D” into the next available node This insertion may cause our tree to not be a heap anymore!!!
“D” is smaller then “H”. So, Swap positions “D” is not smaller then “C” so the heap is complete
Removing from the Heap Always take the root node.
Since the smaller Child of “L” is “D” -> Swap “D” and “L”
Since the smaller Child of “L” is “H” -> Swap “L” and “H”
Final Conclusions • Heapsort doesn’t require much memory space! • Heapsort is very fast! • Quicksort > Heapsort • Mergesort > Heapsort • Heapsort + Quicksort = Introsort • Introsort > (Quicksort || Heapsort)
Check out these cool links • http://tide4javascript.com/?s=Heapsort • http://cis.stvincent.edu/html/tutorials/swd/heaps/heaps.html • http://en.wikipedia.org/wiki/Heapsort • SWEET animation: http://www2.hawaii.edu/~copley/665/HSApplet.html