Heapsort, Priority Queues




CS146

Chris Pollett

Feb 26, 2014

Outline

Introduction

Maintaining the Max-Heap Property

Remarks on MAX-HEAPIFY

An example of the MAX-HEAPIFY

Runtime of MAX-HEAPIFY

Building a Heap

BUILD-MAX-HEAP Example

A sequence of trees illustrating BUILD-MAX-HEAP

Heapsort

We now give the pseudo-code for a sorting algorithm based on heaps. On the next slide we give some intuition and estimate its runtime.

HEAPSORT(A)
1 BUILD-MAX-HEAP(A)
2 for i = A.length downto 2
3     exchange A[1] with A[i]
4     A.heap-size = A.heap-size - 1
5     MAX-HEAPIFY(A, 1)

Remarks on Heapsort

Heapsort Example

A sequence of trees illustrating HEAPSORT in action

Priority Queues

Example use of a Max Priority Queue

Example use of a Min-Priority Queue

Auxiliary data

Using Heaps for Priority Queues

Below is max-heap pseudo-code for each of the priority queue operations. We give the run-times as comments.

HEAP-MAXIMUM(A)
// This is an O(1) algorithm
1 return A[1] 
HEAP-EXTRACT-MAX(A)
// This is an O(log n) algorithm
1 if A.heap-size < 1
2     error "heap underflow"
3 max = A[1]
4 A[1] = A[A.heap-size]
5 A.heap-size = A.heap-size - 1
6 MAX-HEAPIFY(A,1)
7 return max
HEAP-INCREASE-KEY(A, i, key)
// This is an O(log n) algorithm
1 if key < A[i]
2     error "new key is smaller than current key"
3 A[i] = key
4 while i > 1 and A[parent(i)] < A[i]
5     exchange A[i] with A[Parent(i)]
6     i = Parent(i)
MAX-HEAP-INSERT(A, key)
// This is an O(log n) algorithm
1 A.heap-size = A.heap-size + 1
2 A[A.heap-size] = - infty
3 HEAP-INCREASE-KEY(A, A.heap-size, key)