1.基本特性:
最差时间复杂度:O(n*logn)
最优时间复杂度:O(n*logn)
平均时间复杂度:O(n*logn)
空间复杂度(辅助内存):O(1)
稳定性:不稳定
2.基本思想:
堆排序(HeapSort)是利用堆这种数据结构设计的排序算法。堆近似于完全二叉树,而且满足堆的性质:子节点的值总是小于(或大于)其父节点的值。
通常堆是通过一维数组来实现的。在起始数组下标为0的情况下:
父节点 i 的左子节点 为 ( 2*i + 1 );
父节点 i 的右子节点 为 ( 2*i + 2 );
子节点 i 的父节点位置在 floor ( ( i-1 ) /2);
步骤(升序):
1.根据待排数组的长度,计算出最后一个父节点的位置,然后一次对每个节点进行调整,使整个数组成为一个大根堆。
2.将大根堆的根节点的值和数组最后一个节点值交换。然后从根节点进行调整。
3.然后将数组的长度减1,执行上面两步,直到数组长度为1。
3.代码实现(C语言)
void HeapAdjust(int a[], int position, int length)
{
int child = 2 * position + 1;
int temp;
for(int p = position; child < length ; child = 2*p + 1)
{
if(child+1 <length && a[child+1]>a[child])
++child;
if(a[p]<a[child])
{
temp = a[p];
a[p] = a[child];
a[child] = temp;
}
else
break;
p = child;
}
}
void HeapSort(int a[], int length)
{
if(a == NULL || length <= 1)
return;
for(int i = (length-1)/2; i >=0; --i)
{
HeapAdjust(a,i,length);
}
int temp = a[length-1];
a[length-1] = a[0];
a[0] = temp;
while(length>1)
{
--length;
HeapAdjust(a,0,length);
HeapSort(a,length);
}
}