Presentation is loading. Please wait.

Presentation is loading. Please wait.

Heap structure Pasi Fränti 29.9.2014. Tree-based data structure Partial sorting Every node satisfies heap property: x ≥ x.child zy x 87 7 5 43215 9 Max.

Similar presentations


Presentation on theme: "Heap structure Pasi Fränti 29.9.2014. Tree-based data structure Partial sorting Every node satisfies heap property: x ≥ x.child zy x 87 7 5 43215 9 Max."— Presentation transcript:

1 Heap structure Pasi Fränti 29.9.2014

2 Tree-based data structure Partial sorting Every node satisfies heap property: x ≥ x.child zy x 87 7 5 43215 9 Max Heap as priority queue Example: y ≤ xz ≤ x 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(); Heapsort Straightforward implementation O(1) O(N logN) Requires O(N) extra space for the heap 7 4 6 1 8 … 1 4 6 7 8 … Insert Remove

4 Heapsort Inplace variant i 2i 2i+1 1 2 3 4 5 6 7 8 9 … … 23 4 5 67 89 1 Indexing in heap: Indexing in list: Use array itself as heap (no extra memory) Heap is always balanced Father-son relationships calculated via indexes Father(i) i =  k/2  LeftChild(i) k 1 = 2i RightftChild(i)k 2 = 2i+1

5 Heapsort Inplace variant Heapsort(A[1,N]) FOR i  N/2 DOWNTO 1 DO Sink(A, i, N); FOR i  N DOWNTO 2 DO Swap(A[1],A[i]); Sink(A, 1, i-1); List Heap i List Heap ListHeap i Insert Remove Swap i Loop Heap List Sink i 1

6 Sink function 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); Select bigger child Left child exists Right child exists Swap if needed Sink recursively

7 Example of sink Added value 1 87 7 5 43215 1 Added 17 7 5 43215 8 Swap 77 1 5 43215 8  

8 Heap creation is linear time i n Sink(i,n) 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 12 1 345 2 log N N Rectangle total Difference

10 Empty space for notes

11

12 Another example 100 9374 92 936765 9122 354352717 Just back-up


Download ppt "Heap structure Pasi Fränti 29.9.2014. Tree-based data structure Partial sorting Every node satisfies heap property: x ≥ x.child zy x 87 7 5 43215 9 Max."

Similar presentations


Ads by Google