View
225
Download
0
Category
Preview:
DESCRIPTION
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 … … Insert Remove
Citation preview
Heap structurePasi Fränti
29.9.2014
• Tree-based data structure• Partial sorting• Every node satisfies heap
property:x ≥ x.child
zy
x
87
7
5
43 2 15
9
Max
Heap as priority queue
Example:
y ≤ x z ≤ x
HeapHeap
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)
Requires O(N) extra space for
the heap
7 4 6 1 8 …
1 4 6 7 8 …
Insert
Remove
HeapsortInplace variant
i
2i 2i+1
1 2 3 4 5 6 7 8 9 …
…
2 34 5 6 7
8 9
1
Indexingin 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) k1 = 2iRightftChild(i) k2 = 2i+1
HeapsortInplace variant
Heapsort(A[1,N])FOR iN/2 DOWNTO 1 DO
Sink(A, i, N);FOR iN DOWNTO 2 DO
Swap(A[1],A[i]);Sink(A, 1, i-1);
List Heapi
List
Heap
List
Heap i
Insert
Remove
Swap
iLoop
Heap
List
Sinki
1
Sink function
Sink(A, i, j)IF 2i ≤ j THEN
IF 2i+1 ≤ j THENIF A[2i]>A[2i+1] THEN k2i ELSE k=2i+1;
ELSEk2i;
IF A[i]<A[k] THENSwap(A[i], A[k]);Sink(A, k, j);
Select bigger child
Left child existsRight child exists
Swap if neededSink recursively
Example of sinkAdded value 1
87
7
5
43 2 15
1Added
17
7
5
43 2 15
8Swap
77
1
5
43 2 15
8
Swap
n
i
n
i
n
i
inn
inniT
jiTcjiT
1
1 1
loglog
)log(log),(
),2(),(
Heap creation is linear time
iilog
nlogn
Sink(i,n)
• Half of the elements need no work• Next half only one level• Element at location i needs (logn - logi) work
n
i
inn1
loglog
Heap creation is linear time
1 2
1
3 4 5
2
log N
N
N
i
i1
log
nnnnnnnnnn
dxxnnn
loglogloglog
)(loglog1
Rectangle total
Difference nO
Empty space for notes
Empty space for notes
Another example
100
93 74
92 93 67 65
9122 22 35 43 5 27 17
Just back-up
Recommended