最近学习一下堆排序,自己在理解了思想后尝试写了一下,开始还觉得写的不错,但后来看了大牛的代码,顿时觉得自己的代码丑陋的没法再说了。所以按照大牛的代码写了一下,参考http://blog.kingsamchen.com/archives/547#viewSource,个人对他上面的代码稍微缩减了一点,觉得更美了一点点。。。。
最大堆,从小到大排序代码:
#include <iostream>
#define lson(key) ((key << 1) + 1)
#define rson(key) ((key + 1) << 1)
#define perent(key) ((key - 1) >> 1)
// #define perent(key) (((key + 1) >> 1) - 1)
using namespace std;
void MaxHeapify(int tree[], int key, int length){//保持最大堆的性质,三个参数,数组,检查的起始下标和堆大小
int left = lson(key), right = rson(key), flag = key;
if(left <= length && tree[flag] < tree[left])
flag = left;
if(right <= length && tree[flag] < tree[right])
flag = right;
if(flag != key){
swap(tree[key], tree[flag]);
MaxHeapify(tree, flag, length);
}
}
void BuildMaxHeap(int tree[], int length){//把原数组调整成最大堆
for(int i = perent(length); i >= 0 ; --i)
MaxHeapify(tree, i, length);
}
void HeapSort(int tree[], int length){//堆排序主函数
BuildMaxHeap(tree, length - 1);
for(int i = length - 1; i > 0; --i){
swap(tree[0], tree[i]);
MaxHeapify(tree, 0, i - 1);
}
}
int main(){
int tree[10] = {9,12,17,30,50,20,60,65,4,49};
HeapSort(tree, 10);
for(int i = 0;i < 10; i ++)
cout << tree[i] << " ";
cout << endl;
}