堆排序
一、概念
基础概念:堆排序是利用堆这种数据结构而设计的一种排序算法,堆排序是一种选择排序,它的最坏,最好,平均时间复杂度均为O(nlogn),它也是不稳定排序。
通俗理解:
将待排序序列构造成一个大顶堆,此时,整个序列的最大值就是堆顶的根节点。将其与末尾元素进行交换,此时末尾就为最大值。然后将剩余n-1个元素重新构造成一个堆,这样会得到n个元素的次小值。如此反复执行,便能得到一个有序序列了
二、代码及过程
/**
*
*堆排序
*
*Date:2019年5月5日
*
***/
#include <stdio.h>
// 调整二叉堆
void downAdjust(int *a,int parent,int length){
int temp = a[parent]; // 保存当前节点的值
int child = 2 * parent + 1;
// 开始调整
while(child < length){
// 如果存在右孩子,并且右孩子大于左孩子,那么定位到右孩子
if((child + 1) < length && a[child + 1] > a[child]){
child++;
}
// 如果当前节点大于或等于左右孩子的话,直接退出
if(temp >= a[child]){
break;
}
// 直接覆盖,无需交换
a[parent] = a[child];
parent = child;
child = 2 * child + 1;
}
a[parent] = temp;
}
// 堆排序
void heapSort(int *a,int length){
int i = (length - 2) / 2; // 定位到最后一个非叶子节点
int temp;
// 1.构建最大堆
for(; i >= 0; i--){
downAdjust(a,i,length);
}
// 2.堆排序
for(i = length - 1; i > 0; i--){
temp = a[0];
a[0] = a[i];
a[i] = temp;
downAdjust(a,0,i);
}
}
// 输出
void show(int *a,int n){
int i;
for(i = 0; i < n; i++){
printf("%3d",a[i]);
}
}
void main(){
int a[] = {1,3,2,6,5,7,8,9,10,0};
int length = sizeof(a) / sizeof(a[0]);
printf("\n排序前:\n");
show(a,length);
// 堆排序
heapSort(a,length);
printf("\n排序后:\n");
show(a,length);
printf("\n");
}
三、复杂度
平均时间复杂度: O(nlogn)
空间复杂度: O(1)