#include<iostream.h>
#include<ctype.h>
class heap
{
public:
heap( int);
void insert( const int &);
const int& get_delMin(int &);
void print(int[],int);
private:
int Size;
int* array;
int cap;
void percolateDown( int hole );
};
void heap::print(int in[],int size )
{
cout<<"\tInserted Elements\tSorted Elements\n"<<endl;
for(int i=1;i<=size-1;i++)
{
cout<<"\t\t"<<in[i]<<"\t\t\t"<<this->get_delMin(array[0])<<endl;
}
}
heap::heap( int cap)
{
array = new int[cap + 1];
Size=0;
}
void heap::insert( const int & x )
{
int hole = ++Size;
for(; hole > 1 && x < array[hole/2 ]; hole /= 2)
array[ hole ] = array[ hole / 2 ];
array[hole] = x;
}
const int& heap::get_delMin(int& x )
{
x = array[ 1 ];
array[ 1 ] = array[ Size-- ];
percolateDown( 1 );
return x;
}
void heap::percolateDown( int hole )
{
int child;
int tmp = array[ hole ];
for( ; hole * 2 <= Size;hole = child)
{
child = hole * 2;
if( child != Size && array[child+1] < array[ child ] )
child++;
if( array[ child ] < tmp )
array[ hole ] = array[ child ];
else
break;
}
array[ hole ] = tmp;
}
main(int argc, char *argv[])
{
if (argc > 1)
{
if(isdigit(*(argv[1])))
{
heap h(argc);
int ar2[argc];
for(int i=1;i<=argc;i++)
{
ar2[i]=atoi((argv+i)[0]);
}
for(int i=0;i<argc;i++)
{
h.insert(ar2[i]);
}
cout<<"\n\tSorted Elements are:\n"<<endl;
h.print(ar2,argc);
}
}
else if(argc<=1)
{
cout<<"Heap is empty"<<endl;
cout<<" or"<<endl;
cout<<"Zero Elements are inserted through Command Prompt"<<endl;
cout<<"Please open it through Command Prompt & "<<endl;
cout<<"Insert Elements Through Command Line Argument\n\n\n\n\n"<<endl;
}
cout<<"\n\n\n\n";
system("pause");
}
No comments:
Post a Comment