80 likes | 213 Views
6.3.1 Heapsort. Idea: two phases: 1. Construction of the heap 2. Output of the heap For ordering number in an ascending sequence: use a Heap with reverse order: the maximum number should be at the root (not the minimum). Heapsort is an in-situ-Procedure.
E N D
6.3.1 Heapsort Idea:two phases: 1. Construction of the heap 2. Output of the heap For ordering number in an ascending sequence: use a Heap with reverse order: the maximum number should be at the root (not the minimum). Heapsort is an in-situ-Procedure
Remembering Heaps: change the definition Heap with reverse order: • For each node x and each successor y of x the following holds: m(x) m(y), • left-complete, which means the levels are filled starting from the root and each level from left to right, • Implementation in an array, where the nodes are set in this order (from left to right) .
Second Phase: Heap 2. Output of the heap: take n-times the maximum (in the root, deletemax) and exchange it with the element at the end of the heap. Heap is reduced by one element and the subsequence of ordered elements at the end of the array grows one element longer. cost: O(n log n). Heap Ordered elements Ordered elements
First Phase: 1. Construction of the Heap: simple method: n-times insert Cost: O(n log n). making it better: consider the array a[1 … n ] as an already left-complete binary tree and let sink the elements in the following sequence ! a[n div 2] … a[2] a[1] (The elements a[n] … a[n div 2 +1] are already at the leafs.) HH The leafs of the heap
Formally: heap segment an array segment a[ i..k ] ( 1 ik <=n ) is said to be a heapsegment when following holds: for all j from {i,...,k} m(a[ j ]) m(a[ 2j ]) if 2j k and m(a[ j ]) m(a[ 2j+1]) if 2j+1 k If a[i+1..n] is already a heap segment we can convert a[i…n] into a heap segment by letting a[i] sink.
Cost calculation Be k = [log n+1]+ - 1. (the height of the complete portion of the heap) cost: For an element at level j from the root: k – j. alltogether: {j=0,…,k} (k-j)•2j = 2k•{i=0,…,k} i/2i =2 • 2k = O(n).
advantage: The new construction strategy is more efficient ! Usage: when only the m biggest elements are required: 1. construction in O(n) steps. 2. output of the m biggest elements in O(m•log n) steps. total cost: O( n + m•log n).
Addendum: Sorting with search trees Algorithm: • Construction of a search tree (e.g. AVL-tree) with the elements to be sorted by n insert opeartions. • Output of the elements in InOrder-sequence. Ordered sequence. cost: 1. O(n log n) with AVL-trees, 2. O(n). in total: O(n log n). optimal!