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

    堆排序,要从初始状态调整成大顶堆,然后每次取出顶(此时顶是最大的),用最后一个元素代替顶,再接着排序。

    #define LOCAL
    #include<cstdio>
    #include<cstdlib>
    #include<iostream>
    using namespace std;
    typedef int ElemType;
    const int maxSize=10;
    //从结点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 i;
        ElemType temp;
        for(i=n/2;i>=1;--i)
        {
            Sift(R,i,n);
        }
        for(i=n;i>=1;--i)
        {
            temp=R[1];
            R[1]=R[i];
            R[i]=temp;
            Sift(R,1,i-1);
        }
    }
    void outPut(ElemType R[],int n)
    {
        for(int i=1;i<=n;i++)
        {
            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 i;
        for(i=1;i<=maxSize;i++)
        {
            cin>>R[i];
        }
        heapSort(R,maxSize);
        outPut(R,maxSize);     
        return 0;
    }
  • 相关阅读:
    元组类型内置方法
    python的两种编程模式
    Python和Python解释器
    异常处理
    文件的三种打开方式
    python解释器的安装
    编程语言的分类
    计算机基础之编程
    linux 安装postgresql
    CentOS7 部署 gitlab
  • 原文地址:https://www.cnblogs.com/jianfengyun/p/4015878.html
Copyright © 2011-2022 走看看