Sunday, 26 April 2015

Cpp Program for sorting elements using Heap Sort


This is a Cpp Program which sorts all the elements using Heap Sort technique.

Look at the below animation ,

Heapsort-example.gif
"Heapsort-example" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons.




Download Code
PROGRAM : 
#include <iostream>

using namespace std;

int main()
{
    int heap[10], no, i, j, c, root, temp;

    cout << "How many numbers? \t";
    cin  >> no;
    cout << "\n\n";
    for (i = 0; i < no; i++)
    {
        cout << "Enter number "<< i+1 <<" :\t";
        cin >> heap[i] ;
    }

    for (i = 1; i < no; i++)
    {
        c = i;
        do
        {
            root = (c - 1) / 2;
            if (heap[root] < heap[c])
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            c = root;
        }
        while (c != 0);
    }

    cout << "\n\nThe Heap array  is: \n\n";
    for (i = 0; i < no; i++)
        cout << heap[i] << "\t";
    for (j = no - 1; j >= 0; j--)
    {
        temp = heap[0];
        heap[0] = heap[j];
        heap[j] = temp;
        root = 0;
        do
        {
            c = 2 * root + 1;
            if ((heap[c] < heap[c + 1]) && c < j-1)
                c++;
            if (heap[root]<heap[c] && c<j)
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            root = c;
        }
        while (c < j);
    }
    cout << "\n\nThe sorted array is : \n\n";
    for (i = 0; i < no; i++)
        cout << heap[i] << " \t";
    return 0;
}


Download Code
OUTPUT :
Cpp - Heap Sort