码迷,mamicode.com
首页 > 其他好文 > 详细

Sort

时间:2014-10-12 21:15:28      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   for   strong   数据   

bubuko.com,布布扣

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

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

 

Sort

标签:style   blog   http   color   io   os   for   strong   数据   

原文地址:http://www.cnblogs.com/jianfengyun/p/4020936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!