sailing

Everything...

Heap Sort

// HeapSort.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <iostream>

 

void DirectSelectSort(int* a, int iLen);

void HeapSort(int* a, int iLen);

void FilterDown(int* a, int iStart, int iEnd);

void PrintArray(int a[], int iLen);

void Swap(int* a, int index1, int index2);

 

int _tmain(int argc, _TCHAR* argv[])

{

    int arrayToSort[] = {20, 7, 3, 4, 25, 15, 29, 12, 4, 1};

    int n = sizeof(arrayToSort)/sizeof(int);

    PrintArray(arrayToSort, n);

    HeapSort(arrayToSort, n);

    PrintArray(arrayToSort, n);

    return 0;

}

 

void HeapSort(int* a, int iLen)

{

    if(a==NULL||iLen<=0)

       return;

    //  Initialize to a heap

    int i;

    for(i=(iLen-2)/2;i>=0;i--)

    {

       FilterDown(a,i,iLen-1);

    }

    for(i=iLen-1;i>=1;i--)

    {

       Swap(a, i, 0);

       FilterDown(a,0,i-1);

    }

}

 

void FilterDown(int* a, int iStart, int iEnd)

{

    if(iStart>=iEnd) return;

    int iParent = iStart;

    int iChild = iParent*2+1;

    while(iChild<=iEnd)

    {

       if(iChild<iEnd)

           if(a[iChild]<a[iChild+1])

              iChild += 1;

       if(a[iParent]<a[iChild])

       {

           Swap(a,iParent, iChild);

           iParent = iChild;

           iChild = 2*iChild +1;

       }

       else

       {

           break;

       }

    }

}

 

void Swap(int* a, int index1, int index2)

{

    if(index1!=index2&&a!=NULL)

    {

       int temp = a[index1];

       a[index1] = a[index2];

       a[index2] = temp;

    }

}

 

void PrintArray(int a[], int iLen)

{

    for(int i=0; i< iLen; i++)

    {

       std::cout<<a[i]<<' ';

    }

    std::cout<<std::endl;

}

posted on 2007-01-29 00:10  乌生鱼汤  阅读(196)  评论(0编辑  收藏  举报

导航