Computer Sciences 1 HEAP SORT TUTORIAL 4 Computer

  • Slides: 19
Download presentation
Computer Sciences 1

Computer Sciences 1

HEAP SORT TUTORIAL 4 Computer Sciences 2

HEAP SORT TUTORIAL 4 Computer Sciences 2

Objective • O(n lg n) worst case like merge sort. • Sorts in place

Objective • O(n lg n) worst case like merge sort. • Sorts in place like insertion sort. • A heap can be stored as an array A. • Root of tree is A[1]. • Parent of A[i ] = A[i/2]. • Left child of A[i ] = A[2 i ]. • Right child of A[i ] = A[2 i + 1]. • Computing is fast with binary representation implementation.

Heap data structure Heap is a nearly complete binary tree. “Heap is almostcomplete binary

Heap data structure Heap is a nearly complete binary tree. “Heap is almostcomplete binary tree. ” Height of node = # of edges on a longest simple path from the node down to a leaf. Height of heap = height of root = (lg n). Computer Sciences 4

Maintaining the heap property Computer Sciences 5

Maintaining the heap property Computer Sciences 5

Building a heap (a bottom-up manner) Computer Sciences 6

Building a heap (a bottom-up manner) Computer Sciences 6

The heap-sort algorithm Computer Sciences 7

The heap-sort algorithm Computer Sciences 7

Exercises Illustrate the operation of heap. Sort on the below array: {17, 1, 9,

Exercises Illustrate the operation of heap. Sort on the below array: {17, 1, 9, 14, 2, 8, 3} 1 17 17 1 4 14 2 3 5 6 2 8 9 1 7 3 14 Computer Sciences a) 9 8 8 2 b) 3

17 17 1 14 14 9 2 8 1 3 c) Computer Sciences 9

17 17 1 14 14 9 2 8 1 3 c) Computer Sciences 9 8 2 d) 9 3

17 14 14 1 9 2 8 3 1 e) Computer Sciences 9 3

17 14 14 1 9 2 8 3 1 e) Computer Sciences 9 3 2 8 f) 10 17

9 8 3 1 3 8 2 14 1 17 g) Computer Sciences 2

9 8 3 1 3 8 2 14 1 17 g) Computer Sciences 2 9 14 h) 11 17

2 3 1 8 1 2 9 14 17 8 i) Computer Sciences 3

2 3 1 8 1 2 9 14 17 8 i) Computer Sciences 3 9 14 j) 12 17

1 Sorted 2 3 1 8 9 14 3 8 17 l) k) Computer

1 Sorted 2 3 1 8 9 14 3 8 17 l) k) Computer Sciences 2 13 9 14 17

Exercises Build a max. Heap from the below array: {15, 9, 20, 13, 4,

Exercises Build a max. Heap from the below array: {15, 9, 20, 13, 4, 59} 1 15 15 9 4 13 2 3 5 20 9 6 4 59 13 Computer Sciences 20 a) 14 59 4 b)

15 15 9 9 13 59 13 4 4 20 20 c) Computer Sciences

15 15 9 9 13 59 13 4 4 20 20 c) Computer Sciences 59 d) 15

15 15 13 13 9 59 4 9 20 e) Computer Sciences 59 4

15 15 13 13 9 59 4 9 20 e) Computer Sciences 59 4 20 f) 16

59 59 13 13 9 15 9 4 15 4 20 h) g) Computer

59 59 13 13 9 15 9 4 15 4 20 h) g) Computer Sciences 20 17

CONCLUSION Computer Sciences 18

CONCLUSION Computer Sciences 18

CONCLUSION Computer Sciences 19

CONCLUSION Computer Sciences 19