You can also use the following coding for the Heap Code in C++ programming language :
Code:
header file:
#ifndef HEAP_H
#define HEAP_H
class heap
{
friend ostream &operator<<( ostream&, const heap & );
private:
Type *array;
int MaxSize, Nel;
void Adjust(Type a[], int i, int n);
public:
heap(int MSize):
heap (const heap &);
~heap();
heap &operator+ (const heap &);
heap &operator+=(const heap &);
heap &operator+ (int );
operator=( const heap &);
operator[]( int);
bool Insert(Type item);
bool DelMax(Type& item);
};
#endif
cpp file:
#include <iostream>
#include "heap.h"
using namespace std;
heap:: heap(int size)
MaxSize(MSize)
{
array = new Type[MaxSize+1];
Nel=0;
};
heap::~heap()
{
delete []array;
};
heap::heap (const heap &a)
{
array=new Type [MaxSize+1];
for (int i=0;i=MaxSize;i++)
array[i]=a[i];
}
friend ostream &operator<<( ostream &output, const heap &a)
{
int i;
for ( i = 0; i = a.MaxSize; i++ ) {
output << setw( 12 ) << a.array[ i ];
if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output
output << endl;
}
if ( i % 4 != 0 ) // end last line of output
output << endl;
return output; // enables cout << x << y;
}
const heap::heap &operator+ (const heap &heap1)
{
Type *array1;
int x=sizeof(heap1)/4;
array1=new[Maxsize+2+x];
for (int i=0;i=MaxSize;i++)
array1[i]=array[i];
for (i=Maxsize;i=x+MaxSize;i++)
array1[i]=heap1.array[i-MaxSize];
delete []array1;
};
const heap::heap &operator+=(const heap &right)
{
Type *array1;
MaxSize1=MaxSize;
array=new Type[MaxSize+1];
for (int i=0;i=MaxSize;i++)
array1[i]=array[i];
delete []array;
MaxSize=MaxSize1+sizeof(right.array)/4;
Type *array;
array=new Type[MaxSize+1];
for (i=0;i=MaxSize1;i++)
array[i]=array1[i];
for (i=MaxSize1+1;i=MaxSize;i++)
array[i]=right.array[i-MaxSize-1];
}
const heap::heap &operator+ (int x)
{
MaxSize=Maxsize+1;
array[MaxSize]=x;
}
const heap &heap::operator=( const heap &right )
{
if ( &right != this )
{
if ( MaxSize != right.size )
{
delete [] array; // reclaim space
MaxSize = right.MaxSize;
array = new int[ MaxSize ];
}
for ( int i = 0; i < MaxSize; i++ )
array[ i ] = right.array[ i ];
}
return *this;
}
int &heap::operator[]( int subscript )
{
if ( subscript < 0 || subscript >= MaxSize ) {
cout << "\nError: Subscript " << subscript
<< " out of range" << endl;
exit( 1 );
}
return array[ subscript ];
}
bool heap::Insert(Type item)
{
int i = ++Nel;
if (i==MaxSize)
{
cout << "heap size exceeded"
<< endl;
return false;
}
while ((i>1) && (array[i/2]<item))
{
array[i] = array[i/2];
i /= 2;
}
array[i] = item;
return true;
}
void heap::Adjust(Type a[], int i, int n)
{
int j = 2*i, item = a[i];
while (j <= n)
{
if ((j<n) && (a[j]<a[j+1]))
j++;
if (item >= a[j])
break;
a[j/2] = a[j];
j *= 2;
}
a[j/2] = item;
}
bool heap::DelMax(Type& item)
{
if (!Nel)
{ cout << "heap is empty"<< endl;
return false;
}
item=array[1];
array[1]=array[Nel--];
Adjust(array, 1, Nel);
return true;
};
Bookmarks