Sie sind auf Seite 1von 9

Start with unordered array of data

Array representation:
21 15 25 3

12 7

19 45 2

Binary tree representation:


21
15

25

19

45

12

9
Prof. Gayathri. P, SCSE, VIT University

Max heap for sorting in ascending order


Min heap for sorting in descending order
Let us sort in ascending order
21

21

15
3

25
5

19 45 2

12

15
7

25
9

19 45 2

15 3 2

25
12
5

45

25
9

19 3 2

19
15 3 2

25
9

21

45
7

12
5

21

21
9

12

15

45
19

21

12
5

Prof. Gayathri. P, SCSE, VIT University

15
7

45
19 3 2

25
9

12

5
2

25

45
21

19
15

9
3

21

25

12

19

12
9

25 21 12 19 9 5 7 15 3 2 45

25

21

21

12
9

15 3 2

45 21 25 19 9 12 7 15 3 2 5

19

19
7

15 3 2
25 21 12 19 9 5 7 15 3 2 45

15

12
9

21 19 12 15 9 5 7 2 3 25 45

21

19

19
15
2

12
9

15

12
9

21 19 12 15 9 5 7 2 3 25 45

19 15 12 3 9 5 7 2 21 25 45

19

15

15
3

12
9

9
7

12
2

2
19 15 12 3 9 5 7 2 21 25 45

15 9 12 3 2 5 7 19 21 25 45

Prof. Gayathri. P, SCSE, VIT University

15

12

9
3

12
2

9
7

15 9 12 3 2 5 7 19 21 25 45

7
2

12 9 7 3 2 5 15 19 21 25 45

12
9
3

7
2

12 9 7 3 2 5 15 19 21 25 45

7
2

9 5 7 3 2 12 15 19 21 25 45

and finally

2 3 5 7 9 12 15 19 21 25 45

Prof. Gayathri. P, SCSE, VIT University

Heapsort (A) -> sorts an array in place


Build_max_heap (A)
for i = length(A) down to 2
exchange A[1] <-> A[i]
heap_size[A] = heap_size[A] 1
Max_heapify (A,1)
Build_max_heap (A) -> produces max heap from an unsorted input array
heap_size[A] = length[A]
for i = |_ Length[A] /2 _| down to 1
do Max_heapify [A,i]

Prof. Gayathri. P, SCSE, VIT University

Max_heapify [A,i] -> maintains max heap property


l = Left(i)
r = Right(i)
if l<=heap_size[A] and A[l] > A[i] then
largest = l
else
largest = i
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)

Prof. Gayathri. P, SCSE, VIT University

A queue is first in, first out

A priority queue is least-first-out


The smallest element is the first one removed
(You could also define a largest-first-out priority queue)
If there are several smallest elements, the

implementer must decide which to remove first


Remove any smallest element (dont care which)
Remove the first one added

Prof. Gayathri. P, SCSE, VIT University

A priority queue can be implemented as a heap


least-first-out priority queue satisfies Min heap Minimum

element has more priority


largest-first-out priority queue satisfies Max heap Maximum
element has more priority
Let the priority of any 3 elements be 3, 8, 12

12
8

largest-first-out
priority queue

12

least-first-out priority
queue

Prof. Gayathri. P, SCSE, VIT University

Das könnte Ihnen auch gefallen