Question: c + + Write a function that takes two heaps and merges them into one heap using the heap class provided. #ifndef HEAP _ H

c++ Write a function that takes two heaps and merges them into one heap using the heap class provided.
#ifndef HEAP_H
#define HEAP_H
#include
#include
using namespace std;
template
class Heap {
public:
vector values;
int root(){
return 0;
}
int last(){
return this->values.size()-1;
}
int left(int index){
return index *2+1;
}
int right(int index){
return index *2+2;
}
int parent(int index){
return (index -1)/2;
}
int size(){
return this->values.size();
}
void swap(int indexOne, int indexTwo){
TYPE temp = values[indexOne];
values[indexOne]= values[indexTwo];
values[indexTwo]= temp;
}
bool hasLargerChild(int index){
return (this->left(index)< this->size() &&
values[index]< values[this->left(index)])
||
(this->right(index)< this->size() &&
values[index]< values[this->right(index)]);
}
int largerChild(int index){
if(this->right(index)>= this->size())
return this->left(index);
if(values[this->left(index)]> values[this->right(index)])
return this->left(index);
else
return this->right(index);
}
void print(){
for(TYPE value : values){
cout << value <<"";
}
cout << endl;
}
void insert(TYPE value){
values.push_back(value);
int newIndex = this->last();
while(newIndex >0 &&
values[newIndex]> values[this->parent(newIndex)]){
this->swap(newIndex, this->parent(newIndex));
newIndex = this->parent(newIndex);
}
}
void remove(){
this->swap(this->root(), this->last());
values.pop_back();
int parentIndex =0, largerChildIndex =0;
while(this->hasLargerChild(parentIndex)){
largerChildIndex = largerChild(parentIndex);
swap(parentIndex, largerChildIndex);
parentIndex = largerChildIndex;
}
}
TYPE read(){
return values[this->root()];
}
};
#endif

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!