130 likes | 288 Views
Pasi Fränti. Heap structure. 9.10.2013. 9. 7. 8. 5. 3. 5. 7. 4. 2. 1. x. y. z. Heap as priority queue. Tree-based data structure Partial sorting Every node satisfies heap property : x ≥ x.child. Example:. Max. y ≤ x. z ≤ x. Heap. Heap. Heapsort (A[1,N])
E N D
Pasi Fränti Heap structure 9.10.2013
9 7 8 5 3 5 7 4 2 1 x y z Heap as priority queue • Tree-based data structure • Partial sorting • Every node satisfies heap property: x ≥ x.child Example: Max y ≤ x z ≤ x Heap Heap
Heapsort(A[1,N]) H CreateHeap(); FOR i1 TO N DO Insert(H, A[i]); FOR iN DOWNTO 1 DO A[i] RemoveMax(); HeapsortStraightforward implementation O(1) O(N logN) O(N logN) 7 4 6 1 8 … Insert Requires O(N) extra space for the heap Remove 1 4 6 7 8 …
i 2i+1 2i 1 2 3 4 6 7 5 … 8 9 1 2 3 4 5 6 7 8 9 … HeapsortInplace variant • Use array itself as heap (no extra memory) • Heap is always balanced • Father-son relationships calculated via indexes Indexingin heap: Father(i) i = k/2 LeftChild(i) k1 = 2i RightftChild(i) k2 = 2i+1 Indexing in list:
List Heap i HeapsortInplace variant Heapsort(A[1,N]) FOR iN/2 DOWNTO 1 DO Sink(A, i, N); FOR iN DOWNTO 2 DO Swap(A[i],A[i]); Sink(A, 1, i-1); Insert List Loop Remove Insert i i Heap List i Heap Remove
Sink function Left child exists Sink(A, i, j) IF 2i ≤ j THEN IF 2i+1 ≤ j THEN IF A[2i]>A[2i+1] THEN k2i ELSE k=2i+1; ELSE k2i; IF A[i]<A[k] THEN Swap(A[i], A[k]); Sink(A, k, j); Right child exists Select bigger child Swap if neededand sink recursively
Added 8 8 1 7 7 7 1 7 8 5 5 5 Swap 3 3 3 5 5 5 7 1 7 4 4 4 2 2 2 1 1 1 Swap Example of sinkAdded value 1
i Sink(i,n) n Heap creation is linear time • Half of the elements need no work • Next half only one level • Element at location i needs (logn - logi) work
Heap creation is linear time Rectangle total log N Difference 2 1 N 1 2 3 4 5
Another example Just back-up 100 93 74 92 93 67 65 22 91 22 35 43 5 27 17