Wednesday, 11 October 2017

Implementation of Minimum Heap Tree in C++

Program Code: 
#include <iostream>
using namespace std;
void heapify(int array[], int n, int i)
{
    int largest = i;  
    int l = 2*i + 1;  
    int r = 2*i + 2;  
    if (l < n && array[l] > array[largest])
        largest = l;
    if (r < n && array[r] > array[largest])
        largest = r;
    if (largest != i)
    {
        swap(array[i], array[largest]);
        heapify(array, n, largest);
    }
}
void heap_Sort(int .array[], int n)
{                                                                                
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(array, n, i);

       for (int i=n-1; i>=0; i--)
    {
               swap(array[0], array[i]);
               heapify(array, i, 0);
    }
}
void print_Array(int array[], int n)
{
    for (int i=0; i<n; ++i)
        cout << array[i] << " ";
    cout << "n"; 
}
int main()
{
    int array[] = {22, 11, 23, 15, 56, 77};
    int n = sizeof(array)/sizeof(array[0]);
    cout<<n<<endl;
    Heap_Sort(array, n);
    cout << "Sorted array is n";
    print_Array(array, n);
}

The program output is tested on www.jdoodle.com 
Output:
6
Sorted array is 11 15 22 23 56 77


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput