zoukankan      html  css  js  c++  java
  • 堆算法(make_heap,push_heap,pop_heap, sort_heap)

    算法:对vector进行堆排序
    // range heap example
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    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 max heap   : " << v.front() << endl;
    
      pop_heap (v.begin(),v.end()); v.pop_back();
      cout << "max heap after pop : " << v.front() << endl;
    
      v.push_back(99); push_heap (v.begin(),v.end());
      cout << "max heap after push: " << v.front() << endl;
    
      sort_heap (v.begin(),v.end());
    
      cout << "final sorted range :";
      for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
    
      cout << endl;
    
      return 0;
    }
    

    输出:

    initial max heap   : 30
    max heap after pop : 20
    max heap after push: 99
    final sorted range : 5 10 15 20 99
    

    参考:

    http://www.cplusplus.com/reference/algorithm/

    http://www.cplusplus.com/reference/algorithm/push_heap/

    函数说明:

    std::make_heap将[start, end)范围进行堆排序,默认使用less<int>, 即最大元素放在第一个。

    std::pop_heap将front(即第一个最大元素)移动到end的前部,同时将剩下的元素重新构造成(堆排序)一个新的heap。

    std::push_heap对刚插入的(尾部)元素做堆排序

    std::sort_heap将一个堆做排序,最终成为一个有序的系列,可以看到sort_heap时,必须先是一个堆(两个特性:1、最大元素在第一个 2、添加或者删除元素以对数时间),因此必须先做一次make_heap.

  • 相关阅读:
    Java入门——day42
    第六周进度报告
    Java入门——day41
    Java入门——day40
    Java入门——day39
    Java入门——day38
    Java入门——day37
    Java入门——day36
    Java入门——day35
    第五周进度报告
  • 原文地址:https://www.cnblogs.com/coderyoyo/p/stl_heap.html
Copyright © 2011-2022 走看看