Docsity

Heaps and Heapsort - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Heaps and Heapsort - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Heaps and Heapsort

Heaps

  • Heap Definition.
  • Adding a Node.
  • Removing a Node.
  • Array Implementation.
  • Analysis
  • Source Code.

Heaps

A heap is a certain kind of

complete binary tree. It is

defined by the following

properties.

Heaps (Priority Queues)

A heap is a data structure which supports efficient implementation of three operations: insert, findMin, and deleteMin. (Such a heap is a min-heap, to be more precise.)

Two obvious implementations are based on an array (assuming the size n is known) and on a linked list. The comparisons of their relative time complexity are as follows:

insert findMin deleteMin Sorted array O( n ) O(1) O(1) (from large (to move (find at end) (delete the end) to small) elements) Linked list O(1) O(1) O( n ) (append) (a pointer to Min) (reset Min pointer)

Heaps

2. All levels of

the tree, except

for the bottom

level are

completely filled.

All nodes on the

bottom level

occur as far left

as possible.

Left child of the root

The second node is always the left child of the root.

Heaps

3. The key of

the root node

is greater than

or equal to the

key of each

child. Each

subtree is also

a heap.

Right child of the root

The third node is always the right child of the root.

Heaps

The next nodes always fill the next level from left-to-right.

Heaps

Complete

binary

tree.

Heaps

A heap is a

certain kind

of

complete

binary tree.

The "heap property" requires that each node's key is >= the keys of its children

Heaps

This tree is

not a heap.

It breaks rule

number 1.

Heaps

This tree is

not a heap.

It breaks rule

number 3.

Heap implementation of priority

queue

  • Each node of the heap contains one entry along with

the entry’s priority, and the tree is maintained so

that it follows the heap storage rules using the

entry’s priorities to compare nodes. Therefore:

  • The entry contained by a node has a priority that is

greater than or equal to the priority of the entries of

the nodes children.

  • The tree is a complete binary tree.

Adding a Node to a Heap

 Push the new

node upward,

swapping with its

parent until the

new node reaches

an acceptable

location.

Adding a Node to a Heap

 Push the new

node upward,

swapping with its

parent until the

new node reaches

an acceptable

location.