notes_COSqueues

Heap ordered l r e 6 exch1 xch1 11 sink1 10 sink1

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

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

Unformatted text preview: S 1 2 heap construction 11) X T exch(1, 3) sink(1, 2) X T S M P O heap construction E start with array of keys L E in arbitrary order M S R Heapsort demo E L X T ・Create max-heap with all N keys. exch(1, 9) R S ・Repeatedly remove the maximum key. sink(1, 8) 11) E A R O E Basic plan for in-placeMsort. E E exch(1, 4) sink(1, 3) S E T OX P X 32 Heapsort: constructing (left) and sorting down (ri 31 sink(3, 11) S exch(1, 9) sink(1, 8) R exch(1, 3) sink(1, 2) E Heapsort: sortdown Heapsort: Java implementation sortdown heap construction Second pass. 1 2 S 3 R X 7 ・Remove the maximum, one at a time. ・Leave in array, instead of nulling out. 4 8 O 5 T 9 10 6 E A sink(4, 11) exch(1, 10) sink(1, 9) S L T sink(3, 11) exch(1, 9) sink(1, 8) S L T sink(2, 11) P exch(1, 7) sink(1, 6) X S L 1 L A A R R S 2 E T E 4 P 8 X R E E O result (heap-ordered) Heapsort: constructing (left) and sorting down (right) a heap 9 3 5 S 10 private static void exch(Object a, int i, int j) { /* as before */ } A E L P O X T S R private static boolean less(Comparable a, int i, int j) { /* as before */ } E O M T P A M L X T S R A E private static void sink(Comparable a, int k, int N) { /* as before */ } P O X E E M E E sink(1, 11) M A R M T S exch(1, 2) sink(1, 1) P L E L R O X A E X exch(1, 8) sink(1, 7) S L O L T S but make static (and pass arguments) E A E P X T S O exch(1, 3) sink(1, 2) R O M T M A R E E P E M L R P X A E X T E M O M L E A R P X T S O exch(1, 4) sink(1, 3) S O E E P A X E M A R P R A R X E E M O M L L E S O E E exch(1, 5) sink(1, 4) T P O X T S R public class Heap { public static void sort(Comparable a) { int N = a.length; for (int k = N/2; k >= 1; k--) sink(a, k, N); while (N > 1) { exch(a, 1, N); sink(a, 1, --N); } } E E A E E O starting point (heap-ordered) P A X A R exch(1, 11) sink(1, 10) S L P M R T M L M L S P 11 O while (N > 1) { exch(a, 1, N--); sink(a, 1, N); } T E L P M starting point (arbitrary order) sink(5, 11) exch(1, 6) sink(1, 5) X M 6 O E 7 P } 11 X T result (sorted) but convert from 1-based indexing to 0-base indexing 33 Heapsort: trace 34 Heapsort: mathematical analysis N k initial values 2 O O 3 R R Proposition. Heap construction uses ≤ 2 N compares and exchanges. 11 5 1 S S 11 11 4 3 S S O O R X T T L L X R A A M M P P E E 7 A A 8 M M S X T T X S P P L L R R A A M M O O E E E E X T S R P T P P P O S S R E E P O O O M L L L L L R R E E E A A A A A Proposition. Heapsort uses ≤ 2 N lg N compares and exchanges. E E MOEE...
View Full Document

Ask a homework question - tutors are online