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

  • 相关阅读:
    @responseBody注解的使用
    springmvc下的省市县三级联动
    select 动态添加option函数
    清空select标签中option选项的4种不同方式
    javascript删除option选项的多种方法总结
    js如何获取select下拉框的value以及文本内容
    如何设置select下拉禁止选择
    java.sql.SQLSyntaxErrorException: ORA-00911: 无效字符
    转:通过他人完成任务的艺术
    ***周鸿祎谈创业:很多程序员高智商 但我一看就知道他们不会成功
  • 原文地址:https://www.cnblogs.com/hbt19860104/p/2678339.html
Copyright © 2011-2022 走看看