Implementation


#include <iostream>
using namespace std;

void heapify(int a[], int n, int i)
{
    int large = i;       // Initialize large as root
    int left =( 2 * i) ;  // left child
    int right = (2 * i) + 1; // right child
    // If left child is larger than root
    if (left < n && a[left] > a[large])
        large = left;
    // If right child is larger than root
    if (right < n && a[right] > a[large])
        large = right;
    // If root is not large
    if (large != i)
    {
        // swap a[i] with a[large]
        swap(a[large], a[i]);

        heapify(a, n, large);
    }
}
/*Function to implement the heap sort*/
void heapSort(int a[], int n)
{

    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(a, n, i);
    // One by one extract an element from heap
    for (int i = n - 1; i >= 0; i--)
    {
        /* Move current root element to end*/
        // swap a[0] with a[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