Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

5. What decision-making model would you advocate to this person?

Answered: 1 week ago

Question

6. What data will she need?

Answered: 1 week ago

Question

1. How did you go about making your selection?

Answered: 1 week ago