// heap.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>//heap algorithms
using namespace std;
int main(int argc, char* argv[])
{
int i = 0;
//底层是个list
int ia[9] = {0, 1, 2, 3, 4, 8, 9, 3, 5};
vector<int> ivec(ia, ia + 9);
for(i = 0; i < ivec.size(); ++i)
cout<<ivec[i]<<' ';//0 1 2 3 4 8 9 3 5
cout<<endl;
make_heap(ivec.begin(), ivec.end());
for(i = 0; i < ivec.size(); ++i)
cout<<ivec[i]<<' ';//9 5 8 3 4 0 2 3 1(堆排序的大根堆)
cout<<endl;
ivec.push_back(7);
push_heap(ivec.begin(), ivec.end());
for(i = 0; i < ivec.size(); ++i)
cout<<ivec[i]<<' ';//9 7 8 3 5 0 2 3 1 4(堆排序)
cout<<endl;
pop_heap(ivec.begin(), ivec.end());//根节点和最后一个叶子节点互换
cout<<ivec.back()<<endl;//9
ivec.pop_back();//删除最后一个叶节点
for(i = 0; i < ivec.size(); ++i)
cout<<ivec[i]<<' ';//8 7 4 3 5 0 2 3 1(堆排序去掉根节点的方法相同)
cout<<endl;
sort_heap(ivec.begin(), ivec.end());//从小到大排序,一个递增序列
for(i = 0; i < ivec.size(); ++i)
cout<<ivec[i]<<' ';//0 1 2 3 3 4 5 7 8
cout<<endl;
//底层是个array(不能动态添加元素成员)
for(i = 0; i < 9; ++i)
cout<<ia[i]<<' ';//0 1 2 3 4 8 9 3 5
cout<<endl;
make_heap(ia, ia + 9);
for(i = 0; i < 9; ++i)//9 5 8 3 4 0 2 3 1
cout<<ia[i]<<' ';
cout<<endl;
sort_heap(ia, ia + 9);//经过排序的heap不再是个合法的heap
for(i = 0; i < 9; ++i)
cout<<ia[i]<<' ';//0 1 2 3 3 4 5 7 8 9
cout<<endl;
make_heap(ia, ia + 9);
for(i = 0; i < 9; ++i)
cout<<ia[i]<<' ';//9 8 5 3 3 4 2 1 0
cout<<endl;
pop_heap(ia, ia + 9);
for(i = 0; i < 9; ++i)
cout<<ia[i]<<' ';//8 3 5 3 0 4 2 1 9
cout<<endl;
cout<<ia[8]<<endl;//9
//printf("Hello World!/n");
return 0;
}