堆算法(make_heap,push_heap,pop_heap, sort_heap)

算法:对vector进行堆排序
1
// range heap example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}

输出:

 

1
2
3
4
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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值