12
COMP5712 Tutorial 4

COMP5712

Embed Size (px)

DESCRIPTION

COMP5712. Tutorial 4. Using an Array to Represent a Heap. When a binary tree is complete Can use level-order traversal to store data in consecutive locations of an array Enables easy location of the data in a node's parent or children - PowerPoint PPT Presentation

Citation preview

Page 1: COMP5712

COMP5712

Tutorial 4

Page 2: COMP5712

2

Using an Array to Represent a Heap

• When a binary tree is complete– Can use level-order traversal to store data in

consecutive locations of an array• Enables easy location of the data in a node's

parent or children– Parent of a node at i is found at i/2

(unless i is 1)– Children of node at i found at indices

2i and 2i + 1

Page 3: COMP5712

3

Using an Array to Represent a Heap

(a) A complete binary tree with its nodes numbered in level order; (b) its representation as an array.

Page 4: COMP5712

4

Adding an Entry

A revision of steps of addEntry to avoid swaps.

Page 5: COMP5712

5

Adding an Entry I

An array representation of the steps in previous slide … continued →

Page 6: COMP5712

6

Adding an Entry II

An array representation of the steps

Page 7: COMP5712

7

Removing the Root

The steps to remove the entry in the root of the maxheap

Page 8: COMP5712

8

Heapsort

• Possible to use a heap to sort an array• Place array items into a maxheap• Then remove them– Items will be in descending order– Place them back into the original array and they

will be in order

Page 9: COMP5712

9

Heapsort

A trace of heapsort (a – c)

Page 10: COMP5712

10

Heapsort

A trace of heapsort (d – f)

Page 11: COMP5712

11

Heapsort

A trace of heapsort (g – i)

Page 12: COMP5712

12

Heapsort

A trace of heapsort (j – l)