(算法导论排序算法部分第一个就介绍堆排序,也得复习复习。)
Wiki(http://zh.wikipedia.org/wiki/%E5%A0%86%E6%8E%92%E5%BA%8F#C.E8.AF.AD.E8.A8.80)上也有介绍及代码实现,基本上都是一样的。
摘录堆排序定义如下:
堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆性质:即子结点的键值或索引总是小于(或者大于)它的父节点。然后实现代码如下:
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
#define ARRAY_SIZE 1000
#define LEFT_CHILD(i) (2 * i)
#define RIGHT_CHILD(i) (2 * i + 1)
int data[ARRAY_SIZE];
//前提root的左右子树都是最大堆
//用来平衡最大二叉堆
//找出最大子树根,然后替换,递归
void Max_Heapify(int data[], int root, int heapSize)
{
int leftchild = LEFT_CHILD(root);
int rightchild = RIGHT_CHILD(root);
int largestchild;
if (leftchild < heapSize && data[leftchild] > data[root])
{
largestchild = leftchild;
}
else
{
largestchild = root;
}
if (rightchild < heapSize && data[largestchild] < data[rightchild])
{
largestchild = rightchild;
}
if (largestchild != root)
{
swap(data[largestchild], data[root]);
Max_Heapify(data, largestchild, heapSize);
}
}
//构建最大二叉堆
//从倒数第二层开始平衡最大堆即可
void Build_Max_Heap(int data[], int heapSize)
{
for (int i = (heapSize - 1) / 2; i >= 0; i--)
{
Max_Heapify(data, i, heapSize);
}
}
//堆排序
//先构建最大二叉堆,然后再每次把根和最后一个节点替换,递归
void HeapSort(int data[], int heapSize)
{
Build_Max_Heap(data, heapSize);
for (int i = heapSize - 1; i > 0; i--)
{
swap(data[0], data[i]);
Max_Heapify(data, 0, i);
}
}
void Printn(int data[], int size)
{
for (int i = 0; i < size; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
void Getn(int data[], int size)
{
for (int i = 0; i < size; i++)
{
cin >> data[i];
}
}
int main()
{
int size;
while (true)
{
cout << "Please input the data szie(no more than " << ARRAY_SIZE << "):(0 to quit.)";
cin >> size;
if (0 == size)
{
break;
}
Getn(data, size);
HeapSort(data, size);
Printn(data, size);
}
}