Build Heap, Heap code in Cpp - Data Stuctures - Lecture Slides, Slides of Data Structures and Algorithms

BuildHeap, Other Heap Operations, Heap code in C , Min heap, Lowers the value, Opposite of decreaseKey, Removes the node, General algorithm, Array, Binary tree are key points of this lecture and you can learn some other data structure terms.

Typology: Slides

2011/2012

Uploaded on 11/03/2012

ekna
ekna 🇮🇳

4.2

(5)

75 documents

1 / 16

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
BuildHeap
The general algorithm is to place the N
keys in an array and consider it to be an
unordered binary tree.
The following algorithm will build a heap
out of N keys.
for( i = N/2; i > 0; i-- )
percolateDown(i);
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Build Heap, Heap code in Cpp - Data Stuctures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

BuildHeap

 The general algorithm is to place the N

keys in an array and consider it to be an

unordered binary tree.

 The following algorithm will build a heap

out of N keys.

for( i = N/2; i > 0; i-- )

percolateDown(i);

BuildHeap

i = 15/2 = 7

i

i

Why I=n/2?

BuildHeap

i = 6

i

i

BuildHeap

i = 5

i

i

BuildHeap

i = 3

i

i

BuildHeap

i = 2

i

i

BuildHeap

Min heap

Other Heap Operations

 decreaseKey(p, delta) :

lowers the value of the key at position ‘p’ by the

amount ‘delta’. Since this might violate the heap order,

the heap must be reorganized with percolate up (in

min heap) or down (in max heap).

 increaseKey(p, delta) :

opposite of decreaseKey.

 remove(p) :

removes the node at position p from the heap. This is

done by first decreaseKey(p, ) and then performing

deleteMin().

Heap code in C++

private:

int currentSize; // Number of elements in heap

eType array; // The heap array*

int capacity;

void percolateDown( int hole );

Heap code in C++

#include "Heap.h“

template

Heap::Heap( int capacity )

array = new etype[capacity + 1];

currentSize=0;

Heap code in C++

template

void Heap::deleteMin( eType & minItem )

if( isEmpty( ) ) {

cout << "heap is empty.“ << endl ;

return;

minItem = array[ 1 ];

array[ 1 ] = array[ currentSize-- ];

percolateDown( 1 );