题目:https://pintia.cn/problem-sets/1268384564738605056/problems/1289169858763866112
题解:https://blog.csdn.net/qq_38996065/article/details/79919366
代码:
#include<stdio.h> #include<math.h> #define MAX 100000 typedef long ElementType; void Swap( ElementType *a, ElementType *b ) { ElementType t = *a; *a = *b; *b = t; } void PercDown( ElementType A[], int p, int N ) { /* 将N个元素的数组中以A[p]为根的子堆调整为最大堆 */ int Parent, Child; ElementType X; X = A[p]; /* 取出根结点存放的值 */ for( Parent=p; (Parent*2+1)<N; Parent=Child ) { Child = Parent * 2 + 1; if( (Child!=N-1) && (A[Child]<A[Child+1]) ) Child++; /* Child指向左右子结点的较大者 */ if( X >= A[Child] ) break; /* 找到了合适位置 */ else /* 下滤X */ A[Parent] = A[Child]; } A[Parent] = X; } void HeapSort( ElementType A[], int N ) { int i; for ( i=N/2-1; i>=0; i-- )/* 建立最大堆 */ PercDown( A, i, N ); for ( i=N-1; i>0; i-- ) { /* 删除最大堆顶 */ Swap( &A[0], &A[i] ); PercDown( A, 0, i ); } } int main() { int i,N; ElementType A[MAX]; scanf("%d",&N); for(i=0;i<N;i++) scanf("%ld",&A[i]); HeapSort(A,N); for(i=0;i<N;i++) { if(i!=0) printf(" "); printf("%ld",A[i]); } return 0; }