寻找大富翁(堆排序)

题目

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值