Heap Sort

#include<iostream>
#include<conio.h>
#define max 50
using namespace std;
int array[max];
int add(int x[],int size)
{
for(int i=2;i<=size;i++)
{
int child=i;
int parent=i/2;
while(array[child]>array[parent]&&child>1)            //while child node is greater then parent node                                                                                                // and child is not root node.
{
int temp=array[child]; //Swapping of parent and child if child is greater then its                                 array[child]=array[parent];       //parent node.
array[parent]=temp;
// cout<<endl<<temp<<" swap with "<<array[child]<<endl;
child=parent; // set child:=parnet
parent=parent/2; // set parent:=parent/2.. because in heap. parent of any position of                 }                                            //child is equal to floor value of its half.
}
}

int main()
{
cout<<"\t\t\t:::::::Heap Sort:::::::\n";
cout<<"How many elements you want to enter?\nAns. ";
int number;
cin>>number;
cout<<"\nEnter elements  > ";
for(int j=1;j<=number;j++)
{
cin>>array[j];
add(array,j);
cout<<"\t\t> ";
}
int numbernew=number;
for(int i=1;i<=numbernew;)
{
int temp=array[i]; //fixing last element as greater element of array.
array[i]=array[numbernew];
array[numbernew]=temp;
numbernew--;
add(array,numbernew);

}
cout<<"\n\nAfter Heap sorting: ";
for(int i=1;i<=number;i++)
cout<<"   "<<array[i];
getch();
return 0;
}
Output: -

How it works




Popular posts from this blog

Shutdown Pc

Ellipse using OpenGl

String Comparisons