C++ program to implement Heap sort Algorithm

#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( ) ;
}

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

  1. srihari

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

    Reply
  2. shravani reddy

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

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

    Reply
  4. Aristotle Doria

    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?

    Reply
  5. Correct me if I am wrong, instead of

    while ( s > 0 && arr[f] 0 && arr[f] < val )
    {
    arr[s] = arr[f] ;
    s = f ;
    f = ( s – 1 ) / 2 ;
    }
    arr[s] = val ;
    void array :: makeheap(int c)
    {

    for ( int i = 1 ; i 0 && arr[f] < val )
    {
    swap(arr, s, f)
    s = f ;
    f = ( s – 1 ) / 2 ;
    }
    }
    }

    Reply
  6. Debabrat

    write a program for priority queue. where all the property will satisfy that means maximum, heap increase key, insertition, deletion , return max operation should present?

    Reply
  7. what is the time complexity is it O(nlogn) or O(n*n). your using two for loops.

    Reply

Leave a Reply