Use a dynamic array for the following code: #include<iostream.h> #include<proces
ID: 3766530 • Letter: U
Question
Use a dynamic array for the following code:
#include<iostream.h>
#include<process.h>
#include<math.h>
#include<iomanip.h>
#include<malloc.h>
struct Heap
{
int capacity;
int size;
int *node;
};
typedef struct Heap *pqueue;
pqueue initialize(int max)
{
pqueue heap;
if(max<3)
{
cout<<“ Priority Queue is too Small ”;
exit(0);
}
heap = new Heap;
if(heap==NULL)
{
cout<<“ Out of Space ”;
exit(0);
}
heap->nodes=new int[((max+1) * sizeof(int))];
if(heap->nodes==NULL)
{
cout<<“ Out of Space ”;
exit(0);
}
heap->capacity = max;
heap->size=0;
heap->nodes[0]=0;
return heap;
}
int isempty(pqueue heap)
{
return (heap->size==0);
}
int isfull(pqueue heap)
{
return(heap->size==heap->capacity);
}
void insert(int x, pqueue heap)
{
int i;
if(isfull(heap))
{
cout<<“ Heap is Full ”;
return;
}
for(i=++heap->size; heap->nodes[i/2] > x; i/=2)
heap->nodes[i]=heap->nodes[i/2];
heap->nodes[i]=x;
}
int deletemin(pqueue heap)
{
int i, child, min, last;
if(isempty(heap))
{
cout<<“ Heap is Empty ”;
return heap->nodes[0];
}
min=heap->nodes[1];
last=heap->nodes[heap->size–];
for(i=1; i*2<=heap->size; i=child)
{
child = i*2;
if(child!=heap->size && heap->nodes[child+1]<heap->nodes[child])
child++;
if(last>heap->nodes[child])
heap->nodes[i]=heap->nodes[child];
else
break;
}
heap->nodes[i]=last;
return min;
}
void main()
{
int size,ch,ele,child;
pqueue heap;
cout<<“ Working with Priority Queues (or) Heaps ”;
cout<<“ Enter the Size of the Heap…”;
cin>>size;
heap = initialize(size);
do
{
cout<<“ Menu ”;
cout<<“ 1. Insert”;
cout<<“ 2. Delete”;
cout<<“ 3. Display”;
cout<<“ 4. Exit”;
cout<<“ Enter Your Choice…”;
cin>>ch;
switch(ch)
{
case 1:
cout<<“ enter element …”;
cin>>ele;
insert(ele, heap);
break;
case 2:
ele=deletemin(heap);
cout<<“ the deleted element is “<<ele<<endl;
break;
case 3:
int space,level=1;
int c=1;
for(int k=1; k<heap->size; k++)
{
for(int j=1;j<=level;j++)
{
if(c<=heap->size)
{
space=(int) (heap->size*2)/c;
cout<<setw(space)<<” “<<heap->nodes[c++]<<setw(space)<<” “;
}
else
break;
}
if (level==1)
level=2;
else if (level>=2)
level=level*2;
cout<<“ ”;
}
break;
default:
cout<<“ Exit “;
}
}while(ch<4);
}
Explanation / Answer
already done
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.