堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
算法步骤:
1. 创建一个堆H[0..n-1]
2. 把堆首(最大值)和堆尾互换
3. 把堆的尺寸缩小1
4. 重复步骤1~3,直到堆的大小为1
动图演示:
算法分析:
时间复杂度: 最佳情况:T(n) = O(nlogn) 最差情况:T(n) = O(nlogn) 平均情况:T(n) = O(nlogn)
空间复杂度: O(1)
稳定性: 不稳定
基于比较的排序算法。
代码实现:
#include<iostream>
using namespace std;
int swap(int *a, int *b) {
int p = *a;
*a = *b;
*b = p;
return 0;
}
int max_heap(int* nums, int i, int length){
if(i==length) return 0;
int li = 2*i+1, ri = 2*i+2, largest = i;
if(li<=length && nums[li]>nums[i])
largest=li;
if(ri<=length && nums[ri]>nums[largest])
largest=ri;
if(largest!=i){
swap(nums[i], nums[largest]);
cout<<"max_heap: nums["<<i<<"]:"<<nums[i]<<" nums["<<largest<<"]:"<<nums[largest]<<endl;
max_heap(nums,largest,length);
}
}
int build_heap(int *nums, int length) {
if (length <= 0) return 0;
for(int i=(length-1)/2; i >=0; i--)
max_heap(nums, i , length);
return 0;
}
int heap_sort(int* nums, int length) {
if (length <= 0) return 0;
while(length >= 0) {
build_heap(nums, length);
for(int i=0; i<=length; i++)
cout << nums[i]<< " ";
cout<<endl;
cout<<"heap_sort: nums[0]:"<<nums[0]<<" nums["<<length<<"]:"<<nums[length]<<endl;
swap(nums[0],nums[length]);
length--;
}
return 0;
}
int main() {
int nums[] = {91,60,96,30,55, 13, 34, 10, 88, 77, 33};
int a=1, b=2;
int length = sizeof(nums)/sizeof(nums[0]);
cout << "sizeof(nums): " << sizeof(nums) << " sizeof(nums[0]): "<<sizeof(nums[0]) << " length:" <<length<<endl;
for(int i=0; i<length; i++)
cout<<nums[i]<< " ";
cout<<endl;
heap_sort(nums, length-1);
for (int i=0; i<length;i++)
cout<<nums[i]<<" ";
cout<<endl;
}