Write a C++, object oriented program that allows the input of 15 animals names a
ID: 3583517 • Letter: W
Question
Write a C++, object oriented program that allows the input of 15 animals names and their corresponding ages. The data should be stored in a max heap, arranged according to their age. The program should then, once the input is complete, create a second heap from the newly created age heap structure using a preorder tree traversal (do not use the original data to do this). This second new max heap should be arranged alphabetically by the animal's name. At this point in the programs execution, both the age heap and name heap should be printed using a breath first search . Finally, once both heaps are complete, a sixth entry, whose age is greater than any previous age (the animals name is your choice), is input, causing both heaps to be heapified. You do not have to be concerned with any deletion from the heaps. Once again output both of the heaps using a breath first search.
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
struct node{
string name;
int age;
node(){} //default constructer
node(string str, int n){ //define constructer
name=str;
age=n;
}
};
class maxHeap{
public:
node *a; //array a of type node
int count;
maxHeap(int size){
a=new node[size+1]; //array size is size+1
count=1; //entry in array start from 1
}
void insert(node newOne){
a[count]=newOne;
balance();
count++;
}
void balance(){
int i=count;
while(i>1){
if(a[i].age>a[i/2].age){
node temp=a[i];
a[i]=a[i/2];
a[i/2]=temp;
i=i/2;
}
else{
break;
}
}
}
void preorderTraversal(){
for(int i=1; i<count; i++){
cout<<a[i].age<<" ";
}
}
};
int main(){
node aradwolf("aradwolf",35);
node buffalo("buffalo",33);
node cat("cat",42);
node dog("dog",10);
node elephant("elephant",14);
node fox("fox",19);
node giraffe("giraffe",27);
node horse("horse",44);
node ibex("ibex",26);
node jaguar("jaguar",31);
maxHeap animalDict(10);
animalDict.insert(aradwolf);
animalDict.insert(buffalo);
animalDict.insert(cat);
animalDict.insert(dog);
animalDict.insert(elephant);
animalDict.insert(fox);
animalDict.insert(giraffe);
animalDict.insert(horse);
animalDict.insert(ibex);
animalDict.insert(jaguar);
animalDict.preorderTraversal();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.