Question

Implement the algorithm Build Heap in C (or C++). Algorithm buildHeap (heap, size) set walker to 1 loop (walker < size) rehea

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// C++ Code to demonstrate the build heap function (Max heap):-

#include<bits/stdc++.h>
using namespace std;
void reheapUp(int heap[],int i)
{
int j=i;
while(j>0)
{
int index=int((j-1)/2);
if(heap[index]<heap[j])
{
swap(heap[index],heap[j]);
j=index;
}
else
break;
}
}

// Implementing function as given in algorithm in question.
// only change is indexing is start with 0 instead of 1.

void buildHeap(int heap[],int size)
{
int walker=0;
while(walker<size)
{
reheapUp(heap,walker);
walker+=1;
}
}
int main()
{
// Declaring array of 30 random values.
int heap[30]={12,36,58,45,13,18,27,26,32,42,57,68,77,82,85,92,96,87,1,17,16,75,46,88,81,55,67,58,99,10};
int i;
  
// Printing array before builiding the heap.
cout<<"Array Before :"<<endl;
for(i=0;i<30;i++)
cout<<heap[i]<<" ";
cout<<endl;
  
// Calling function to build the heap.
buildHeap(heap,30);
cout<<endl;
  
// Printing array after builiding the heap.
cout<<"Array After :"<<endl;
for(i=0;i<30;i++)
cout<<heap[i]<<" ";
cout<<endl;
return 0;
}

main.cpp 1 #include<bits/stdc++.h> 2 using namespace std; 3 void reheapUp(int heap[], int i) 5 int j=i; while(j>o) 6 { 7 8 936 // Printing array before builiding the heap. 37 cout<<Array Before :<<endl; 38 for(i=0;i<30;i++) 39 cout<<heap[i]<< ;

Add a comment
Know the answer?
Add Answer to:
Implement the algorithm Build Heap in C (or C++). Algorithm buildHeap (heap, size) set walker to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT