Question

C++ There is a premade heap.h file. You will write a program that creates a heap,...

C++ There is a premade heap.h file. You will write a program that creates a heap, and then asks the user to enter values which you will put in the heap (at least 8), and then display the heap

Then your program will display a menu with the following choices, and perform the appropriate actions

  1. Display the heap

  2. Add an item to the heap

  3. Remove the largest item

  4. Exit

The program will continue until the user chooses to exit, at which time it will display the heap and exit (and yes, you should have input validation)

heap.h****************************************************************************************************

#ifndef HEAP_H
#define HEAP_H

template <typename datatype>
class heap
{
public:
        void insert(datatype); //inserts at the end, rearranges to keep a heap
        void display(ostream &); //displays the heap
        void removeTop();//removes the top value, rearranges to keep a heap
        datatype top();  //returns the value at the top
        datatype getValue(int); //returns the value at a certain position
        bool empty();  //returns true if the heap is empty
        heap();                 // default constructor
        heap(int);              // constructor passing in size of array
        heap(datatype[], int);  // constructor, passing in array, and size
        ~heap(); //destructor

private:
        void percolateDown(int);
        void percolateUp(int);
        int size=0;
        int maxSize;
        int * myHeap;
};

template <typename datatype>
datatype heap<datatype>::getValue(int position)
{
        return myHeap[position];
}

template <typename datatype>
bool heap<datatype>::empty()
{
        return size == 0;
}
template <typename datatype>
heap<datatype>::heap()
{
        maxSize = 100;
        myHeap= new datatype[maxSize + 1];
}

template <typename datatype>
heap<datatype>::heap(int size)
{
        maxSize = size;
        myHeap = new datatype[maxSize + 1];
}

template <typename datatype>
heap<datatype>::heap(datatype orig[], int arrSize)
{
        maxSize = arrSize*2;
        myHeap = new datatype[maxSize];
        for (int i = 0; i < arrSize; i++)
                insert(orig[i]);
}

template <typename datatype>
heap<datatype>::~heap()
{
        delete []  myHeap;
}

template <typename datatype>
void heap<datatype>::insert(datatype entry)
{
        if (size < maxSize)
        {
                size++;
                myHeap[size] = entry;
                percolateUp(size);
        }
        else
                cout << "No room, couldn't insert\n";
}

template <typename datatype>
void heap<datatype>::percolateUp(int position)
{
        bool done = false;
        while (position/2 > 0 &&!done)
        {
                if (myHeap[position / 2] < myHeap[position])
                {
                        datatype temp = myHeap[position / 2];
                        myHeap[position/2] = myHeap[position];
                        myHeap[position] = temp;
        
                        position = position / 2;
                }
                else
                        done = true;
        }
}

template <typename datatype>
void heap<datatype>::display(ostream &out)
{
        for (int i = 1; i < size + 1; i++)
        {
                cout << myHeap[i] << ' ';
        }
        cout << endl;
}

template <typename datatype>
void heap<datatype>::removeTop()
{
        if (size > 0)
        {
                myHeap[1] = myHeap[size];
                size--;
                percolateDown(1);
        }
        else
                cout << "Heap empty, nothing to remove\n";
}

template <typename datatype>
void heap<datatype>::percolateDown(int position)
{
        if (position * 2 > size)    // no children
                return;

        //set 'bigger child' to be left-child
        int bigChild = position * 2;

        if (position * 2 < size)             //if 2 children
        {   //if right > left, set 'bigger child' to be right
                if (myHeap[position * 2 + 1]>myHeap[position * 2])
                        bigChild++;
        }
        //swap value with that of bigger child, IF NECESSARY
        if (myHeap[bigChild] > myHeap[position])
        {
                //swap value with that of bigger child
                datatype temp = myHeap[position];
                myHeap[position] = myHeap[bigChild];
                myHeap[bigChild] = temp;

                // call percolateDown with the new position (bigChild);
                percolateDown(bigChild);
        }
}
template <typename datatype>
datatype heap<datatype>::top()
{
        if (size>0)
                return myHeap[1];
        datatype junk;
        return junk;
}
#endif
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//heap.h

#ifndef HEAP_H
#define HEAP_H
#include<iostream>
using namespace std;
template <typename datatype>
class heap
{
public:
void insert(datatype); //inserts at the end, rearranges to keep a heap
void display(ostream &); //displays the heap
void removeTop();//removes the top value, rearranges to keep a heap
datatype top(); //returns the value at the top
datatype getValue(int); //returns the value at a certain position
bool empty(); //returns true if the heap is empty
heap(); // default constructor
heap(int); // constructor passing in size of array
heap(datatype[], int); // constructor, passing in array, and size
~heap(); //destructor

private:
void percolateDown(int);
void percolateUp(int);
int size=0;
int maxSize;
int * myHeap;
};

template <typename datatype>
datatype heap<datatype>::getValue(int position)
{
return myHeap[position];
}

template <typename datatype>
bool heap<datatype>::empty()
{
return size == 0;
}
template <typename datatype>
heap<datatype>::heap()
{
maxSize = 100;
myHeap= new datatype[maxSize + 1];
}

template <typename datatype>
heap<datatype>::heap(int size)
{
maxSize = size;
myHeap = new datatype[maxSize + 1];
}

template <typename datatype>
heap<datatype>::heap(datatype orig[], int arrSize)
{
maxSize = arrSize*2;
myHeap = new datatype[maxSize];
for (int i = 0; i < arrSize; i++)
insert(orig[i]);
}

template <typename datatype>
heap<datatype>::~heap()
{
delete [] myHeap;
}

template <typename datatype>
void heap<datatype>::insert(datatype entry)
{
if (size < maxSize)
{
size++;
myHeap[size] = entry;
percolateUp(size);
}
else
cout << "No room, couldn't insert\n";
}

template <typename datatype>
void heap<datatype>::percolateUp(int position)
{
bool done = false;
while (position/2 > 0 &&!done)
{
if (myHeap[position / 2] < myHeap[position])
{
datatype temp = myHeap[position / 2];
myHeap[position/2] = myHeap[position];
myHeap[position] = temp;
  
position = position / 2;
}
else
done = true;
}
}

template <typename datatype>
void heap<datatype>::display(ostream &out)
{
for (int i = 1; i < size + 1; i++)
{
cout << myHeap[i] << ' ';
}
cout << endl;
}

template <typename datatype>
void heap<datatype>::removeTop()
{
if (size > 0)
{
myHeap[1] = myHeap[size];
size--;
percolateDown(1);
}
else
cout << "Heap empty, nothing to remove\n";
}

template <typename datatype>
void heap<datatype>::percolateDown(int position)
{
if (position * 2 > size) // no children
return;

//set 'bigger child' to be left-child
int bigChild = position * 2;

if (position * 2 < size) //if 2 children
{ //if right > left, set 'bigger child' to be right
if (myHeap[position * 2 + 1]>myHeap[position * 2])
bigChild++;
}
//swap value with that of bigger child, IF NECESSARY
if (myHeap[bigChild] > myHeap[position])
{
//swap value with that of bigger child
datatype temp = myHeap[position];
myHeap[position] = myHeap[bigChild];
myHeap[bigChild] = temp;

// call percolateDown with the new position (bigChild);
percolateDown(bigChild);
}
}
template <typename datatype>
datatype heap<datatype>::top()
{
if (size>0)
return myHeap[1];
datatype junk;
return junk;
}
#endif
//main.cpp

#include"heap.h"
#include<iostream>
using namespace std;


int main(){
   heap<int> h(20);
   int num;
   int data;
   int choice;
   cout<<"Enter number of integer element want to put in heap (atleast 8): ";
   cin>>num;
   cout<<"Enter elements in heap\n";
   for(int i=0;i<num;i++){
       cin>>data;
       h.insert(data);
   }
  
   do{
       cout<<"\n(1)Display the heap\n(2)Add an item to the heap\n(3)Remove the largest item\n(4)Exit\n";
       cout<<"Enter choice : ";
       cin>>choice;
       switch(choice){
           case 1:{
               cout<<"heap\n";
               h.display(cout);
               break;
           }
           case 2:{
               cout<<"Enter data : ";
               cin>>data;
               h.insert(data);
               break;
           }
           case 3:{
               cout<<"largest element : "<<h.top()<<" is removed\n\n";
               h.removeTop();
               break;
           }
           case 4:{
               cout<<"Thank you\n";
               break;
           }
           default:{
               cout<<"Invalid input\n";
               break;
           }
       }
      
   }while(choice!=4);
  
   return 0;
  
}

//sample output

Add a comment
Know the answer?
Add Answer to:
C++ There is a premade heap.h file. You will write a program that creates a heap,...
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
  • - implement the Stack ADT using array – based approach. Use C++ program language #include "StackArray.h"...

    - implement the Stack ADT using array – based approach. Use C++ program language #include "StackArray.h" template <typename DataType> StackArray<DataType>::StackArray(int maxNumber) { } template <typename DataType> StackArray<DataType>::StackArray(const StackArray& other) { } template <typename DataType> StackArray<DataType>& StackArray<DataType>::operator=(const StackArray& other) { } template <typename DataType> StackArray<DataType>::~StackArray() { } template <typename DataType> void StackArray<DataType>::push(const DataType& newDataItem) throw (logic_error) { } template <typename DataType> DataType StackArray<DataType>::pop() throw (logic_error) { } template <typename DataType> void StackArray<DataType>::clear() { } template <typename DataType> bool StackArray<DataType>::isEmpty() const {...

  • Please use the linked approach implement the BST ADT, implement all the functions in the BSTree.cpp....

    Please use the linked approach implement the BST ADT, implement all the functions in the BSTree.cpp. Add the ouput of the implementation. use recursive functions to traverse the tree - read the implementation notes on using helper functions. Please use C++ programming ////////////////////////////////////////////////////////////// #include "BSTree.h" template <typename DataType, class KeyType> BSTree<DataType, KeyType>::BSTreeNode::BSTreeNode ( const DataType &nodeDataItem, BSTreeNode *leftPtr, BSTreeNode *rightPtr ) { } template < typename DataType, class KeyType > BSTree<DataType, KeyType>::BSTree () {    root = 0; } template...

  • add/ remove any methods to the program. please post new code and output Min Heap: public...

    add/ remove any methods to the program. please post new code and output Min Heap: public class MinHeap { private int[] Heap; private int size; private int maxsize; private static final int FRONT = 1; public MinHeap(int maxsize) { this.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MIN_VALUE; } private int parent(int pos) { return pos / 2; } private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) {...

  • PROGRAM DESCRIPTION Using the given class definitions for either C++, create a minimum heap that stores...

    PROGRAM DESCRIPTION Using the given class definitions for either C++, create a minimum heap that stores integers and and implements a minimum priority queue. (Your program can be "hard coded" for integers - it does not need to use templates, generics, or polymorphism.) Your data structure must always store its internal data as a heap. Your toString function should return a string with the heap values as a comma separated list, also including the size of the heap as well....

  • can someone please fix this error in the stack file at line 18 ( class Stack2:public...

    can someone please fix this error in the stack file at line 18 ( class Stack2:public Stack { ) this is thew error ----> expected class name before '{' token Queue.h --> #include "Stack.hpp" template <typename ITEM> class Queue { private: ITEM item; Stack <ITEM> * s1= new Stack<ITEM>; Stack <ITEM> * s2= new Stack<ITEM>; public: Queue(){}; bool enqueue (ITEM item); bool dequeue (ITEM &item); bool check = true; ~Queue(); }; //this is the class which contains the functions of...

  • This project is divided into 3 parts: Part 1. Create a new project and download the arrayList and...

    This project is divided into 3 parts: Part 1. Create a new project and download the arrayList and unorderedArrayList templates that are attached. Create a header file for your unorderedSet template and add it to the project. An implementation file will not be needed since the the new class will be a template. Override the definitions of insertAt, insertEnd, and replaceAt in the unorderedSet template definition. Implement the template member functions so that all they do is verify that the...

  • //C++ program #include<iostream> using namespace std; template<typename T> class list{    private:        T*arr;   ...

    //C++ program #include<iostream> using namespace std; template<typename T> class list{    private:        T*arr;        int size;        int capacity;               void resize(){            capacity*=2;            T * newArr = new T[capacity];            for(int i=0;i<size;i++){                newArr[i] = arr[i];            }            delete(arr);            arr = newArr;                   }           public:       ...

  • I'm just not sure how to tackle all the template class this header wants me to...

    I'm just not sure how to tackle all the template class this header wants me to write. I got this far into making the template for public and private and would like help on the template functions. Thank you! This is in C++ by the way. #include <iostream> #include <cassert> using namespace std; #ifndef ARRAYLIST_H #define ARRAYLIST_H template<typename T> class arrayList { public:    arrayList(); //Constructor with default parameter. //Sets maxSize = 100 and length = 0 if no parameter...

  • #ifndef HEAP_H_ #define HEAP_H_ namespace cse { template<typename dtype> class heap { public: /** TO DO::...

    #ifndef HEAP_H_ #define HEAP_H_ namespace cse { template<typename dtype> class heap { public: /** TO DO:: default constructor perform new to reserve memory of size INITIAL_CAPACITY. set num_items = 0; */ heap() { // write your code here }; /** Create a heap from a given array */ heap(dtype *other, size_t len) { // write your code here }; /** copy constructor copy another heap to this heap. */ heap(const heap<dtype> &other) { //write your code here }; /** Accessor...

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