8/12/2019 DataStructure - Heap
1/21
D
. 17
Dr. Seemab Latif
Heap Sorting
8/12/2019 DataStructure - Heap
2/21
2
? D :
1. A , (
)
2. A ,
8/12/2019 DataStructure - Heap
3/21
3
B
:
A n
0 n-2
Balanced Balanced Not balanced
n-2
n-1n
8/12/2019 DataStructure - Heap
4/21
4
A n :
2n
n( ), 2k k, k < n,
n
Left-justified Not left-justified
8/12/2019 DataStructure - Heap
5/21
5
,
,
8/12/2019 DataStructure - Heap
6/21
6
A
A
A
12
8 3
Blue node has heap
property
12
8 12
Blue node has heap
property
12
8 14
Blue node does not have
heap property
8/12/2019 DataStructure - Heap
7/21
7
siftUp ,
14
8 12
Blue node has heap
property
12
8 14
Blue node does not have
heap property
8/12/2019 DataStructure - Heap
8/21
8
C A
:A
,
:
Add a newnode here
Add a newnode here
8/12/2019 DataStructure - Heap
9/21
9
C ,
,
B , ,
, ,
( ),
8/12/2019 DataStructure - Heap
10/21
10
C
8 8
10
10
8
10
8 5
10
8 5
12
10
12 5
8
12
10 5
8
1 2 3
4
8/12/2019 DataStructure - Heap
11/21
11
8 ,
5 ,
8 , ,
12
10 5
8 14
12
14 5
8 10
14
12 5
8 10
8/12/2019 DataStructure - Heap
12/21
12
A
;
19
1418
22
321
14
119
15
25
1722
8/12/2019 DataStructure - Heap
13/21
13
()
:
:
19
1418
22
321
14
119
15
1722
11
8/12/2019 DataStructure - Heap
14/21
14
reHeap ,
,
siftUp()
A ,
19
1418
22
321
14
9
15
1722
11
8/12/2019 DataStructure - Heap
15/21
15
reHeap ( 11)
siftUp()
A ,
19
1418
22
321
14
9
15
1711
22
8/12/2019 DataStructure - Heap
16/21
16
reHeap (
11) :
siftUp()
A ,
,
19
1418
11
321
14
9
15
1722
22
8/12/2019 DataStructure - Heap
17/21
17
reHeap ,
, ()
19
1418
21
311
14
9
15
1722
22
8/12/2019 DataStructure - Heap
18/21
18
?
:B
,
A
:
heapify the array;while the array isnt empty {
remove and replace the root;rehea the new root node
8/12/2019 DataStructure - Heap
19/21
19
:
i 2*i+1
i 2*i+2
19
1418
22
321
14
119
15
25
1722
25 22 17 19 22 14 15 18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12
8/12/2019 DataStructure - Heap
20/21
20
...
...A
, 11( 9)
25 22 17 19 22 14 15 18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12
11 22 17 19 22 14 15 18 14 21 3 9 25
0 1 2 3 4 5 6 7 8 9 10 11 12
8/12/2019 DataStructure - Heap
21/21
21
( 0, 11)...
, ,
, !
22 22 17 19 21 14 15 18 14 11 3 9 25
0 1 2 3 4 5 6 7 8 9 10 11 12
9 22 17 19 22 14 15 18 14 21 3 22 25
0 1 2 3 4 5 6 7 8 9 10 11 12
11 22 17 19 22 14 15 18 14 21 3 9 25
0 1 2 3 4 5 6 7 8 9 10 11 12
...And again, remove and replace the root node