C++ program to implement Heap sort Algorithm

Tuesday, February 1st, 2011
#include <iostream.h>
const int MAX = 10 ;
class array
{
	private :
		int arr[MAX] ;
		int count ;
	public :
		array( ) ;
		void add ( int num ) ;
		void makeheap(int ) ;
		void heapsort( ) ;
		void display( ) ;
} ;
array :: array( )
{
	count = 0 ;
	for ( int i = 0 ; i < MAX ; i++ )
		arr[MAX] = 0 ;
}
void array :: add ( int num )
{
	if ( count < MAX )
	{
		arr[count] = num ;
		count++ ;
	}
	else
		cout << "\nArray is full" << endl ;
}
void array :: makeheap(int c)
{
 
	for ( int i = 1 ; i < c ; i++ )
	{
		int val = arr[i] ;
		int s = i ;
		int f = ( s - 1 ) / 2 ;
		while ( s > 0 && arr[f] < val )
		{
			arr[s] = arr[f] ;
			s = f ;
			f = ( s - 1 ) / 2 ;
		}
		arr[s] = val ;
	}
}
void array :: heapsort( )
{
	for ( int i = count - 1 ; i > 0 ; i-- )
	{
		int ivalue = arr[i] ;
		arr[i] = arr[0] ;
		arr[0]=ivalue;
		makeheap(i);
 
	}
}
void array :: display( )
{
	for ( int i = 0 ; i < count ; i++ )
		cout << arr[i] << "\t" ;
	cout << endl ;
}
void main( )
{
	array a ;
 
	a.add ( 11 ) ;
	a.add ( 2 ) ;
	a.add ( 9 ) ;
	a.add ( 13 ) ;
	a.add ( 57 ) ;
	a.add ( 25 ) ;
	a.add ( 17 ) ;
	a.add ( 1 ) ;
	a.add ( 90 ) ;
	a.add ( 3  ) ;
	a.makeheap(10) ;
	cout << "\nHeap Sort.\n" ;
	cout << "\nBefore Sorting:\n"  ;
	a.display( ) ;
	a.heapsort( ) ;
	cout << "\nAfter Sorting:\n" ;
	a.display( ) ;
}
Avatar of Ranjith

Author Name :
Ranjith

Total : 8 Comments


8 Responses to “C++ program to implement Heap sort Algorithm”

  1. srihari says:

    its simple and very interesting .and can u please implement like those codes with user defined variables..
    i.e giving input at run time…

  2. srihari says:

    please write codes only using “for” loops…

  3. shravani reddy says:

    its easily understandable and i need d pgms of stacks using array and linked lilist and also queues

  4. sunil choudhary says:

    please give the algorithm using max heap

  5. Navaz says:

    Ur code is really understandable..plz give the cpp code for sparse matrix addition and transpose

  6. Aristotle Doria says:

    It’s output is just the same with those in the selection sort. Does the code also works for the selection sort or only for heap sort?

  7. goutham says:

    please use some meaningfull variable names

  8. shani says:

    plz write the code 4 heap sort tht takes input data frm the txt file

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup

Email: