http://blog.csdn.net/morewindows/article/details/6709644/
//HeapSorter.h
#pragma once
#include <stdlib.h>
#include <stdio.h>
class HeapSorter
{
public:
HeapSorter(int nVecLength);
~HeapSorter(void);
protected:
HeapSorter()
{
m_pVect = NULL;
m_nVecLens = 0;
}
public:
void RandomValueVector();
void OutputVector();
void MinHeapSortToDescendArray(); //最小堆的降序排序
protected:
void MinHeapFixup(int *pArr, int i); //数组i元素更新到小堆的插入操作
//调整i节点的位置更新至正确的小堆:小堆的i节点下沉
void MinHeapFixdown(int *pArr, int i, int n);
void MakeMinHeap(int *pArr, int n); //从乱序数组建立最小堆
protected:
int *m_pVect;
int m_nVecLens;
};
//HeapSorter.cpp
#include "HeapSorter.h"
#include <time.h>
#include <assert.h>
HeapSorter::HeapSorter(int nVecLength)
{
m_nVecLens = nVecLength;
if(m_nVecLens > 0)
{
m_pVect = new int[m_nVecLens];
}
else
m_pVect = NULL;
srand(time(NULL));
}
HeapSorter::~HeapSorter(void)
{
if(m_pVect)
{
delete []m_pVect;
m_pVect = NULL;
}
}
void HeapSorter::RandomValueVector()
{
int *ptr=m_pVect;
for(int i=0; i < m_nVecLens; i++)
{
*ptr++ = rand();
}
}
void HeapSorter::MinHeapFixup(int *pArr, int i)
{
assert(pArr && i > 0);
int j, temp;
temp = pArr[i];
j = (i -1) / 2; //父节点
while(j >= 0 && i > 0)
{
if(pArr[j] <= temp)
break;
pArr[i] = pArr[j];
i = j;
j = (i -1) / 2; //父节点
}
pArr[i] = temp;
}
void HeapSorter::MinHeapFixdown(int *pArr, int i, int n)
{
assert(pArr && i >= 0 && n > 0);
int j, temp;
temp = pArr[i];
j = 2*i + 1; //第一个子节点
while(j < n)
{
if(j + 1 < n && pArr[j+1] < pArr[j])
j++;
if(pArr[j] >= temp)
break;
pArr[i] = pArr[j];
i = j;
j = 2*i + 1; //第一个子节点
}
pArr[i] = temp;
}
void HeapSorter::MakeMinHeap(int *pArr, int n)
{
assert(pArr && n > 0);
for(int i = n / 2 - 1; i >= 0; i--)
{
MinHeapFixdown(pArr, i, n);
}
}
void HeapSorter::MinHeapSortToDescendArray()
{
assert(m_pVect && m_nVecLens > 0);
MakeMinHeap(m_pVect, m_nVecLens);
int temp = 0;
for(int i = m_nVecLens - 1; i > 0; i--)
{
temp = m_pVect[i];
m_pVect[i] = m_pVect[0];
m_pVect[0] = temp;
MinHeapFixdown(m_pVect, 0, i);
}
}
void HeapSorter::OutputVector()
{
int lineNum = 20;
for(int i = 0; i < m_nVecLens; i++)
{
printf("%5d", m_pVect[i]);
if(i % lineNum == lineNum - 1)
{
printf("\n");
}
else
printf("\t");
}
printf("\n\n");
}
//main.cpp
#include <stdlib.h>
#include <stdio.h>
#include "HeapSorter.h"
int main()
{
HeapSorter sorter(100);
sorter.RandomValueVector();
sorter.OutputVector();
sorter.MinHeapSortToDescendArray();
sorter.OutputVector();
sorter.RandomValueVector();
sorter.OutputVector();
sorter.MinHeapSortToDescendArray();
sorter.OutputVector();
printf("press any key to exit:");
getchar();
}