Heapsort implementation in C++

//
// heapSort.cpp
// learnCpp
//
// Copyright 2011 __MyCompanyName__. All rights reserved.
//


#include
using namespace std;
void display(int a[], int n)
{
    cout<<" --------------- "<<endl;
    for (int i=0;i<5; ++i) {
        cout<<a[i]<<endl;
    }
}
void heapify(int a[], int n)
{
    int i,j,k,item;
    for(k=1; k0 && item > a[j]) {    // if parent exists and item > parent
            a[i] = a[j];    // move parent down to child
            i = j;
            j = (i-1) / 2;
        }
        a[i] = item;    // insert item into child's position
    }
}
void adjust(int a[], int n)
{
    int i,j,item;
    j=0;    // parent
    item = a[j];
    i = 2*j+1;  // left child - right child can be got by 2*j+2
    while (i <= n-1) {
        if(i+1 <= n-1)      // if right child also exists
            if(a[i] < a[i+1]) i++;  // obtain position of largest child
        if(item 0;i--)
    {
        temp = a[0];
        a[0] = a[i];
        a[i] = temp;
        adjust(a, i);
    }
}
int main (int argc, const char * argv[])
{
    int a[5]={34,8,15,56,90};
    heapsort(a, 5);
    cout<<" ----- Finally ------- "<<endl;
    for (int i=0;i<5; ++i) {
        cout<<a[i]<<endl;
    }
}

In

Leave a Reply

Your email address will not be published. Required fields are marked *