堆排序
2015-03-09 15:45
232 查看
二. 算法描述
堆是一种完全二叉树结构,并且其满足一种性质:父节点存储值大于(或小于)其孩子节点存储值,分别称为大顶堆、小顶堆。堆一般采用数组进行存储(从下标为1开始),则父节点位置为i,那么其左孩子为2*i,右孩子为2*i + 1。 ki≤K2i且ki≤K2i+1或(2)Ki≥K2i且ki≥K2i+1(1≤i≤)
二. 算法分析
平均时间复杂度:O(nlog2n)空间复杂度:O(1) (用于交换数据)
稳定性:不稳定
三. 算法实现
//调整节点 大根堆 //调整节点root,数组共有N个节点
void adjust_heap(int heap[8],int root,int len)
{
if (len == 1 || root > (len-2)/2) //root为叶子节点 (len-2)/2 最后一个非叶子节点的位置
return;
int temp;
int left = 2*root +1;
int right = 2*root +2;
int j;
if (right < len) //说明i有左右两个子节点 三个节点找最大值
{
if (heap[root] >= heap[left] && heap[root] >= heap[right])
return;
if (heap[left] >= heap[right])
{
j = left;
}
else
{
j = right;
}
}
else // 说明i只有左节点 二个节点找最大值
{
if (heap[root] >= heap[left])
return;
else
j = left;
}
temp = heap[j];
heap[j] = heap[root];
heap[root] = temp;
adjust_heap(heap,j,len);
}
//建立堆
void create_heap(int heap[8],int n)
{
for (int i = n/2; i >=0; i--)
{
adjust_heap(heap,i,n);
}
}
//堆排序
void heap_sort(int heap[8],int n)
{
create_heap(heap,n);
for (int i = 0;i <n-1; i++)
{
int temp = heap[n-1-i];
heap[n-1-i] = heap[0];
heap[0] = temp;
adjust_heap(heap,0,n-1-i);
}
}