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

    2017-07-24 22:04:08

    writer:pprp

    参考书目:张新华的《算法竞赛宝典》

    思路跟小根堆一个样,主要的思路是先构造一个大根堆,然后在每次将最大的一个排除出来,再进行堆排序

    代码如下:

    #include <iostream>
    
    using namespace std;
    
    const int maxn = 100;
    int a[maxn],n,heapsize;
    
    void maxheapify(int i)     //根据数组的下表对应节点,对其左右两个子节点进行堆构造;
    {
          int l,r,largest,t;
          l = i<<1;
          r = (i<<1)+1;
          if(l<=heapsize && a[i]<a[l])
                largest = l;
          else
                largest = i;
          if(r<=heapsize && a[r]>a[largest])
                largest = r;
          if(largest!=i)
          {
                t = a[i];
                a[i] = a[largest];
                a[largest] = t;
                maxheapify(largest);
          }
          return;
    }
    
    void BuildMaxHeap()    //建堆
    {
          heapsize = n; //用在heapsort函数中,记录一下n的值;
          for(int i = n/2;i >= 1; i--)
                maxheapify(i);
          return;      
    }
    
    void heapsort()
    {
          int i,t;
          BuildMaxHeap();
          for(i = n;i >= 2;i--)
          {
                t = a[1];
                a[1] = a[i];
                a[i] = t;
                heapsize--;
                maxheapify(1);
          }
    }
    
    int main()
    {
          int i;
          cin >> n;
          for(i = 1; i <= n;i++)
                cin >>a[i];
                
          heapsort();  //建堆主函数
          
          for(i = 1;i <= n;i++)
          {
                cout << a[i] << endl;
          }
        return 0;
    }

    我大部分都是按照书上写的来敲的,所以如果单纯让我写还是有一点困难,之后我得再写一遍。

  • 相关阅读:
    官场22条潜规则,职场谁说不是呢
    pomelo使用中的常见问题
    马斯诺需求金字塔
    Mac上使用brew安装nvm来支持多版本的Nodejs
    Redis 集群解决方案 Codis
    Linux下压缩某个文件夹(文件夹打包)
    使用forever运行nodejs应用
    nodejs npm常用命令
    Mac安装Brew
    C#2.0 迭代器
  • 原文地址:https://www.cnblogs.com/pprp/p/7231419.html
Copyright © 2011-2022 走看看