zoukankan      html  css  js  c++  java
  • 1066-堆排序

    描述

     

    给定输入排序元素数目n和相应的n个元素,写出程序,利用内排序算法中堆排序算法进行排序,并输出排序最后结果的相应序列。

    输入

     

    共两行,第一行给出排序元素数目n,第二行给出n个元素,1n100000,每个元素值范围为 [0100000)

    输出

     

    一行,输出排序结果。

    样例输入

    7

    48 36 68 72 12 48 2

    样例输出

    2 12 36 48 48 68 72

    #include <iostream>
    #define N 100000
    using namespace std;
    void swap(int &x,int &y)
    {
        int z;
        z=x;
        x=y;
        y=z;
    }
    void adjustdown(int a[],int r,int j)
    {
        int child=2*r+1;
        int temp=a[r];
        while(child<=j)
        {
            if((child<j)&&(a[child]<a[child+1]))
                child++;
            if(temp>=a[child]) break;
            a[(child-1)/2]=a[child];
            child=2*child+1;
        }
        a[(child-1)/2]=temp;
    }
    void heapsort(int a[],int n)
    {
        for(int i=(n-2)/2;i>-1;i--)
            adjustdown(a,i,n-1);
        for(int ii=n-1;ii>0;ii--)
        {
            swap(a[0],a[ii]);
            adjustdown(a,0,ii-1);
        }
    }
    int main()
    {
        int n;
        int a[N]={0};
        cin>>n;
    
        for(int k=0;k<n;k++)
            cin>>a[k];
        heapsort(a,n);
        for(int kk=0;kk<n-1;kk++)
            cout<<a[kk]<<" ";
        cout<<a[n-1]<<endl;
    
        return 0;
    }
    

      

  • 相关阅读:
    进程通信
    python模块成像库pillow
    python模块IO
    python模块StringIO和BytesIO
    DJango重写用户模型
    DJango模型Meta选项详解
    DJango中事务的使用
    批量删除文件
    批量修改文件名字或后缀
    自定义中间件实现插拔设计
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3436822.html
Copyright © 2011-2022 走看看