Sort

堆排序没有什么多说的,就是输出的时候最后一个数据后面多一个空格导致输出错误。

//#define LOCAL
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
typedef long ElemType;
const int maxSize=1000000;
//从结点low开始把结点low为根的二叉树调成大根堆 
void Sift(ElemType R[],int low,int hight)
{
    int i=low,j=2*i;
    ElemType temp=R[i];
    while(j<=hight)
    {
        if(j<hight&&R[j]<R[j+1])
        {
            j=j+1;
        }
        if(temp<R[j])
        {
            R[i]=R[j];
            i=j;
            j=2*i;
        }
        else
        {
            break;
        }
    }
    R[i]=temp;
}
//堆排序函数 
void heapSort(ElemType R[],int n,int m)
{
    int i,count=n-m;
    ElemType temp;
    for(i=n/2;i>=1;--i)
    {
        Sift(R,i,n);
    }
    for(i=n;i>count;--i)
    {
        temp=R[1];
        R[1]=R[i];
        R[i]=temp;
        Sift(R,1,i-1);
    }
}
void outPut(ElemType R[],int n,int m)
{
    int count=n-m,i=0;
    for(i=n;i>count;i--)
    {
        if(i!=count+1)
            cout<<R[i]<<" ";
        else cout<<R[i];
    }
    cout<<endl;
}
int main()
{
#ifdef LOCAL
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
#endif    
    ElemType R[maxSize+1];
    int n,m,i;
    while(~scanf("%d%d",&n,&m))
    {
        for(i=1;i<=n;i++)
        {
            cin>>R[i];
        }
        heapSort(R,n,m);
        outPut(R,n,m);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jianfengyun/p/4020936.html