1 / 12

Heap structure

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])

roland
Download Presentation

Heap structure

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pasi Fränti Heap structure 9.10.2013

  2. 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

  3. Heapsort(A[1,N]) H  CreateHeap(); FOR i1 TO N DO Insert(H, A[i]); FOR iN 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 …

  4. 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:

  5. List Heap i HeapsortInplace variant Heapsort(A[1,N]) FOR iN/2 DOWNTO 1 DO Sink(A, i, N); FOR iN 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

  6. 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 k2i ELSE k=2i+1; ELSE k2i; 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

  7. 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  

  8. 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

  9. Heap creation is linear time Rectangle total log N Difference 2 1 N 1 2 3 4 5

  10. Empty space for notes

  11. Empty space for notes

  12. Another example Just back-up 100 93 74 92 93 67 65 22 91 22 35 43 5 27 17

More Related