make_heap,pop_heap,push_heap

一、概念

堆可以看做一个完全二叉树,同时该完全二叉树满足双亲结点大于等于孩子结点(大顶堆),或者双亲结点小于等于孩子结点(小顶堆)。

make_heap: 时间复杂度为O(N)

push_heap: 时间复杂度为O(logN)

pop_heap: 时间复杂度为O(logN)

sort_heap: 时间复杂度为O(NlogN)

二、代码

// range heap example
#include      // std::cout
#include     // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include        // std::vector
using namespace std;
void printnum(vector& nums)
{
    for (int i = 0; i < nums.size(); ++i)
        cout << nums[i] << " ";
    cout << endl;
}
int main () {
  int myints[] = {10,20,30,5,15};
  std::vector v(myints,myints+5);

  std::make_heap (v.begin(),v.end(),less());//默认
  std::cout << "initial max heap   : ";
  printnum(v);
  std::cout << '\n';

  std::make_heap (v.begin(),v.end(),greater());
  std::cout << "initial min heap   : ";
  printnum(v);
  std::cout << '\n';

  std::pop_heap (v.begin(),v.end()); 
  std::cout << "after pop_heap : ";
  printnum(v);
  std::cout << '\n';

  v.pop_back();
  std::cout << "after pop_back : ";
  printnum(v);
  std::cout << '\n';

  v.push_back(99); 
  std::cout << "after push_back : ";
  printnum(v);
  std::cout << '\n';

  std::push_heap(v.begin(),v.end());
  std::cout << "after push_heap : ";
  printnum(v);
  std::cout << '\n';

  return 0;
}

make_heap,pop_heap,push_heap_第1张图片

你可能感兴趣的:(C++)