Upload
tareq-hasan
View
3.444
Download
1
Tags:
Embed Size (px)
Citation preview
Heap Data Structure
The heap data structure is an array object
that can be viewed as a nearly complete
binary tree.
Heap
16
2
98
3
10
7
14
4 1
1
2 3
45 6 7
8 9 10
(a)
Heap
1 2 3 4 5 6 7 8 9 10
16 14 10 8 7 9 3 2 4 1
(b)
Heap
There are two kinds of binary heaps
• max-heaps
• min heaps
Maintaining the Heap Property
The function of MAX-HEAPIFY is to let the
value at A[i] “float down” in the max-heap
so that the sub-tree rooted at index i
becomes a max-heap
Maintaining the Heap Property
MAX-HEAPIFY(A, i)
l LEFT(i)
r RIGHT(i)
if l <= heap-size[A] and A[l] >A [i]
then largest l
else largest i
Maintaining the Heap Property
If r<= heap-size[A] and A[r] > A[largest]
then largest r
If largest ≠ i
then exchange A[i] A[largest]
MAX-HEAPIFY(A, largest)
Maintaining the Heap Property
16
2
914
3
10
7
4
8 1
1
2 3
45 6 7
8 9 10
i
(a)
Maintaining the Heap Property
16
2
94
3
10
7
14
8 1
1
2 3
45 6 7
8 9 10
i
(b)
Maintaining the Heap Property
16
2
96
3
10
7
14
4 1
1
2 3
45 6 7
8 9 10i
(c)
Building a Heap
BUILD-MAX-HEAP(A)
heap-size[A] length[A]
for i length[A]/2 downto 1
do MAX-HEAPIFY(A, i)
Building a Heap
A 4 1 3 2 16 9 10 14 8 7
Building a Heap
4
14
92
10
3
16
1
8 7
1
2 3
45 6 7
8 9 10
i
(a)
Building a Heap
4
14
92
10
3
16
1
8 7
1
2 3
45 6 7
8 9 10
i
(b)
Building a Heap
4
2
914
10
3
16
1
8 7
1
2 3
45 6 7
8 9 10
i
(c)
Building a Heap
4
2
914
3
10
16
1
8 7
1
2 3
45 6 7
8 9 10
i
(d)
Building a Heap
4
2
914
3
10
7
16
8 1
1
2 3
45 6 7
8 9 10
i
(e)
Building a Heap
16
2
98
3
10
7
14
4 1
1
2 3
45 6 7
8 9 10
(f)
Heapsort Algorithm
HEAPSORT(A)
BUILD-MAX-HEAP(A)
for I length[A] downto 2
do exchange A[1] A[i]
heap-size[A] heap-size[A] -1
MAX-HEAPIFY(A,1)
Heapsort Algorithm
16
2
98
3
10
7
14
4 1
(a)
Heapsort Algorithm
14
2
94
3
10
7
8
1
(b)
16i
Heapsort Algorithm
10
2
14
3
9
7
8
(c)
16
i
14
Heapsort Algorithm
9
14
2
3
7
8
(d)
16
i
1410
Heapsort Algorithm
8
14
3
2
7
(e)
16
i
1410
19
Heapsort Algorithm
7
1
3
2
4
(f)
16
i
1410
98
Heapsort Algorithm
4
1
32
(g)
16
i
1410
987
Heapsort Algorithm
3
12
(h)
16
i
1410
9874
Heapsort Algorithm
2
1
(i)
16
i
1410
9874
3
Heapsort Algorithm
1
2
(j)
16
i
1410
9874
3
Heapsort Algorithm
A 1 2 3 4 7 8 9 10 14 16
k