Implementation


#include <iostream>
using namespace std;

void heapify(int a[], int n, int i)
{
    int large = i;      
    int l =( 2 * i) ;
    int r = (2 * i) + 1;

    if (l < n && a[l] > a[large])
        large = l;
    if (r < n && a[r] > a[large])
        large = r;
    if (large != i)
    {
        swap(a[large], a[i]);
        heapify(a, n, large);
    }
}
void heapSort(int a[], int n)
{
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(a, n, i);

    for (int i = n - 1; i >= 0; i--)
    {
        int temp = a[0];
        a[0] = a[i];
        a[i] = temp;

        heapify(a, i, 0);
    }
}
    // Driver code
    int main()
    {
    int a[] = {47, 9, 22, 42, 27, 25, 0};
    int n = 7;
    heapSort(a, n);
    cout << "Sorted array: ";
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
    return 0;
    }
 

Output


Sorted array: 0 9 22 25 27 42 47