堆(排序)算法
make_heap()
:建堆push_heap()
:插入堆元素pop_heap()
:删除堆元素sort_heap()
:堆排序重排成普通排序
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> ivec;
for (int i = 3; i <= 7; ++i)
ivec.push_back(i);
for (int i = 5; i <= 9; ++i)
ivec.push_back(i);
for (int i = 1; i <= 4; ++i)
ivec.push_back(i);
cout << "ivec原始数据:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
make_heap(ivec.begin(), ivec.end());
cout << "ivec按堆排序:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
pop_heap(ivec.begin(), ivec.end());
cout << "取出ivec最大值放到ivec末尾,其余数重新建堆:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
ivec.pop_back();
cout << "删除最大ivec数据:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
ivec.push_back(17);
cout << "在ivec中新增数据:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
push_heap(ivec.begin(), ivec.end());
cout << "新堆数据:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
sort_heap(ivec.begin(), ivec.end());
cout << "堆排序变成普通排序:" << endl;
for (vector<int>::iterator iter = ivec.begin();
iter != ivec.end(); ++iter)
cout << *iter << ' ';
cout << endl;
return 0;
}