堆排序

来源:互联网 发布:破解购物卡数据库 编辑:程序博客网 时间:2024/05/16 08:33

参照算法导论写下来的,有点乱

#include <iostream>#include <fstream>using namespace std;void max(int a[],int i,int m){    int largest,t;    int l=2*i;    int r=2*i+1;    if(l<=m&&a[l]>a[i])        largest=l;    else        largest=i;    if(r<=m&&a[r]>a[largest])       {           largest=r;       }    if(largest!=i)    {         t=a[i];         a[i]=a[largest];         a[largest]=t;         max(a,largest,m);    }}void build(int a[],int n){    int m=n;    for(int i=(n/2);i>=1;i--)    {          max(a,i,m);    }}void sort(int a[],int n){    int t;    int m=n;    for(int i=n;i>=2;i--)    {        t=a[1];        a[1]=a[i];        a[i]=t;        --m;        max(a,1,m);    }}int main (){    int first=1;    int a[100];    while(cin>>a[first++])    {}    build(a,first-2);    sort(a,first-2);    for(int i=1;i<first-1;i++)    {        cout<<a[i]<<' ';    }    return 0;}