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

    make_heap, push_heap, pop_heap, sort_heap

    “堆”定义
      n个关键字序列Kl,K2,…,Kn称为(Heap),当且仅当该序列满足如下性质(简称为堆性质):
      (1)ki<=k(2i)且ki<=k(2i+1)(1≤i≤ n),当然,这是小根堆,大根堆则换成>=号。//k(i)相当于二叉树的非叶结点,K(2i)则是左孩子,k(2i+1)是右孩子
      若将此序列所存储的向量R[1..n]看做是一棵完全二叉树的存储结构,则堆实质上是满足如下性质的完全二叉树:
      树中任一非叶结点的关键字均不大于(或不小于)其左右孩子(若存在)结点的关键字。

     看如下代码:

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <stdarg.h>
    #include <stdio.h>
    using namespace std;

    template <class _T>
    class Dump
    {
    public:
        void operator()(const _T& t){cout << t << ",";}
        //void operator()(_T& t){cout << t << ",";}
    };

    template <class _T>
    void dump_container(const _T& t)
    {
        for_each(t.begin(), t.end(), Dump<typename _T::value_type>());
        cout << endl;
    }

    int main () {
      int myints[] = {10,20,30,5,15};
      vector<int> v(myints,myints+5);
      vector<int>::iterator it;

      make_heap (v.begin(),v.end());
      cout << "initial  : " ;
      dump_container(v);

      pop_heap (v.begin(),v.end()); v.pop_back();
      cout << "max heap after pop : ";
      dump_container(v);

      v.push_back(99); push_heap (v.begin(),v.end());
      cout << "max heap after push: " ;
      dump_container(v);

      sort_heap (v.begin(),v.end());

      cout << "final sorted range :";
      dump_container(v);;

      cout << endl;

      return 0;
    }
     

    输出结果为:

    $ a.exe
    initial  : 30,20,10,5,15,
    max heap after pop : 20,15,10,5,
    max heap after push: 99,20,10,5,15,

    final sorted range :5,10,15,20,99

  • 相关阅读:
    2014-12-13 ~ 2015-11-13
    Burnside引理与polya定理
    HDU 5418 Victor and World (状态压缩dp)
    HDU 5446 Unknown Treasure(lucas + 中国剩余定理 + 模拟乘法)
    HDU 5412 CRB and Queries (整体二分)
    LA 4327 Parade(单调队列优化dp)
    win7远控控制桌面防火墙设置到例外
    win7远控控制桌面
    TCP的三次握手和四次挥手
    ES6 for in与for of 的使用方法及其区别
  • 原文地址:https://www.cnblogs.com/hbt19860104/p/2678339.html
Copyright © 2011-2022 走看看