#include <stdlib.h>
#include <stdio.h>
/* 堆排序 */
void HeapAdjust(int a[],int index,int n)
{ //注意规定a[0]不存放元素,当做缓存用
int i,father = index,son;
a[0] = a[index];
for(son=2*father; son<=n; son*=2)//比较子节点
{
if(son<n && a[son+1] > a[son])son++;//右节点更大
if(a[son] < a[0] )break;//不需要继续了
a[father] = a[son];//大的上提
father = son;
}
a[father] = a[0];
}
void HeapSort(int a[],int n)
{ //注意规定a[0]不存放元素,当做缓存用
int i;
for(i=n/2; i>0; i--)//从最后一个非叶节点开始从下往上建立大顶堆
HeapAdjust(a,i,n);
for(i=n; i>1; i--)//不断抽取堆顶,调整
{
a[0] = a[i];
a[i] = a[1];
a[1] = a[0];
HeapAdjust(a,1,i-1);
}
}
int main(int argc, char *argv[])
{
int a[] = {-1,4,5,3,2,9,8,1,7,6,0};
int i;
HeapSort(a,10);
for(i=1; i<=10; i++)printf("%d\t",a[i]);
printf("\n");
return 1;
}
堆排序(大顶堆->升序)
最新推荐文章于 2023-01-13 23:30:00 发布