Docsity

heap sort data structure, Lecture notes of Design and Analysis of Algorithms

Partial preview of the text

Download heap sort data structure and more Lecture notes Design and Analysis of Algorithms in PDF only on Docsity!

HEAPS

Priority Queues

Linked-list 2 5 8 10 15 āˆ…

head

  • (^) Insert 2 5 8 10 15 āˆ…

head

Time Complexity

Insert:

Delete:

n deletions and

insertions:

O(n)

O(n

O(1)

Heap

A max (min) heap is a complete binary tree such that the data stored in each node is greater (smaller) than the data stored in its children, if any.

Binary Heap: Definition

Binary heap. Almost complete binary tree.

  • (^) filled on all levels, except last, where filled from left to right Min-heap ordered.
  • (^) every child greater than (or equal to) parent 06 14 (^78 ) 91 81 77 45 47 53 (^8384 )

Binary Heap: Properties

Properties. Min element is in root. Heap with N elements has height =  log 2 N . 06 14 (^78 ) 91 81 77 45 47 53 (^8384 )

N = 14

Height = 3

Larger than its parent Not a heap

Missing left child Not a complete tree – Not a heap

1 0001 6 0110 11 1011 2 0010 7 0111 12 1100 3 0011 8 1000 13 1101 4 0100 9 1001 14 1110 5 0101 10 1010 15 1111 After the first 1 from left: 0 – left; 1 –

Next 13

Next 14

Storing a Complete Binary Tree in an Array

for any node at index i parent = i/2 left child = i * 2 right child = i*2+

Binary Heap: Insertion

Insert element x into heap. Insert into next available slot. Bubble up until it's heap ordered.

  • (^) Peter principle: nodes rise to level of incompetence 06 14 (^78 ) 91 81 77 45 47 53 (^83 84 996442) next free slot

Binary Heap: Insertion

Insert element x into heap. Insert into next available slot. Bubble up until it's heap ordered.

  • (^) Peter principle: nodes rise to level of incompetence 06 14 (^78 ) 91 81 77 45 47 42 (^83 84 ) swap with parent

Binary Heap: Insertion

Insert element x into heap. Insert into next available slot. Bubble up until it's heap ordered.

  • (^) Peter principle: nodes rise to level of incompetence 06 14 (^78 ) 91 81 77 42 47 45 (^83 84 ) stop: heap ordered O(log N) operations.