#include<stdio.h>
#define MAXM 10
typedef int ElementType;
void PercDown(ElementType A[],int p,int N);
void HeapSort (ElementType A[],int N);
void InsertionSort(ElementType A[],int n);
void Swap(int *a,int *b);
int main(void)
{
int M,N,i,Temp;
int A[MAXM];
scanf("%d %d",&N,&M);
if (N>MAXM)
{
for (i=0;i<M;i++)
scanf("%d",&A[i]);
for (i=M/2-1;i>=0;i--)
PercDown(A,i,M);
for (i=M;i<N;i++)
{
scanf("%d",&Temp);
if (Temp>A[0])
{
A[0]=Temp;
PercDown(A,0,M);
}
}
HeapSort(A,M);
}
else
{
for (i=0;i<N;i++)
scanf("%d",&A[i]);
InsertionSort(A,N);
}
if (N<M)
M=N;
printf("%d",A[0]);
for (i=1;i<M;i++)
printf(" %d",A[i]);
printf("\n");
return 0;
}
void PercDown(ElementType A[],int p,int N)
{
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++;
if (X<=A[Child])
break;
else
A[Parent]=A[Child];
}
A[Parent]=X;
}
void HeapSort (ElementType A[],int N)
{
int i;
for (i=N-1;i>0;i--)
{
Swap(&A[0],&A[i]);
PercDown(A,0,i);
}
}
void InsertionSort(ElementType A[],int n)
{
int P,i;
ElementType Tmp;
for (P=1;P<n;P++)
{
Tmp=A[P];
for (i=P;i>0&&A[i-1]<Tmp;i--)
A[i]=A[i-1];
A[i]=Tmp;
}
}
void Swap(int *a,int *b)
{
ElementType Temp;
Temp=*a;
*a=*b;
*b=Temp;
}
寻找大富翁(堆排序)
最新推荐文章于 2020-02-10 10:40:45 发布