假设要求从小到大排序
对序列a[n]
1、建立初始大顶堆。
2、输出堆顶元素,即交换a[0]和a[n-1],此时a[n-1]是最大的元素。
有序区为[n-1, n-1],无序区为[0,n-2]。
3、无序区堆结构被破坏,重新调整后再输出堆顶元素。
4、重复2~3,直到无序区只有1个元素。
附简单的C++代码
#include <iostream>
#include <vector>
using namespace std;
#define SWAP_INT(a, b) do{int tmp = a; a = b; b = tmp;}while(0);
class HeapSort
{
public:
HeapSort(vector<int> &a)
{
for(vector<int>::iterator it= a.begin(); it != a.end(); ++it)
{
data.push_