Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

The given simulation is priority queue implementation using heap.

Since you are not specifying a ny


language for implementation, I choose C++

Program

 #include <iostream>

using namespace std;

int H[50];

int size = -1;

int parent(int i) // get parent node index

return (i - 1) / 2;

int leftChild(int i) // get left child of node

return ((2 * i) + 1);

int rightChild(int i) //get right child of node

return ((2 * i) + 2);

void shiftUp(int i) // shift property of heap

while (i > 0 && H[parent(i)] < H[i]) {

swap(H[parent(i)], H[i]); // swap nodes

i = parent(i);

void shiftDown(int i) // shift down to maintain heap

{
int maxIndex = i;

int l = leftChild(i);

if (l <= size && H[l] > H[maxIndex]) {

maxIndex = l;

int r = rightChild(i);

if (r <= size && H[r] > H[maxIndex]) {

maxIndex = r;

if (i != maxIndex) {

swap(H[i], H[maxIndex]);

shiftDown(maxIndex);

void insert(int p) // heap insertion

size = size + 1;

H[size] = p;

shiftUp(size); // call shift up function to insert values

int extractMax() // get element with max. priority

int result = H[0];

H[0] = H[size];

size = size - 1;

shiftDown(0); // shift down the heap to check priority


return result;

void decrement_all(int i, int p) // for decrementing

int oldp = H[i];

H[i] = H[i]-p;

if (p < oldp) {

shiftUp(i);

else {

shiftDown(i);

int getMax() // get maximum element

return H[0];

void remove_min(int i) // remove top element from heap

H[i] = getMax() + 1;

shiftUp(i);

extractMax(); // return the top node

int main()

insert(3);

insert(3);

insert(7);

insert(4);

insert(5);

insert(10);
insert(9);

int i = 0;

// Priority queue before extracting max

cout << "Priority Queue : ";

while (i <= size) {

cout << H[i] << " ";

i++;

cout << "\n";

cout << "Node with maximum priority : "

<< extractMax() << "\n";

cout << "Priority queue after "

<< "extracting maximum : ";

int j = 0;

while (j <= size) {

cout << H[j] << " ";

j++;

cout << "\n";

remove(0);

cout << "Priority queue after "

<< "decrementing the element : ";

int l = 0;

while (l <= size) {

decrement_all(H[l],0 );

cout << H[l]-3<< " ";

l++;

return 0;}

Output

You might also like