#include <iostream>
#include <vector>
using namespace std;
template <class T>
class Heap
{
public:
Heap()
{}
Heap(const T* array, size_t size){
for (size_t i = 0; i < size; i++){
_array.push_back(array[i]);
for (int being = _array.size() / 2 - 1; being >= 0; --being){
_AdjustDown(being);
}
}
}
Heap(vector<T>& array){
_array.swap(array);
for (int being = _array.size() / 2 - 1; being >= 0; --being){
_AdjustDown(being);
}
}
void insert(const T& x){
_array.push_back(x);
_AdjustUp(_array.size() - 1);
}
void MoveHeap(){
_array[0] = _array[_array.size() - 1];
_array.pop_back();
for (int being = _array.size() / 2 - 1; being >= 0; --being){
_AdjustDown(being);
}
}
void Display()
{
for (size_t i = 0; i < _array.size(); i++)
{
cout << _array[i] << " ";
}
cout << endl;
}
protected:
//小堆
//void _AdjustDown(int root){
// int left = root * 2 + 1;
// int right = left + 1;
// while (left<_array.size()){
// int min = left;
// if (right < _array.size() && _array[right] < _array[left]){
// min = right;
// }
// if (_array[min] < _array[root]){
// swap(_array[min], _array[root]);
// root = min;
// left = root * 2 + 1;
// right = root * 2 + 2;
// }
// else{
// break;
// }
// }
//}
//大堆
void _AdjustDown(int root){
int left = root * 2 + 1;
int right = left + 1;
while (left<_array.size()){
int max = left;
if (right < _array.size() && _array[right] > _array[left]){
max = right;
}
if (_array[max] > _array[root]){
swap(_array[max], _array[root]);
root = max;
left = root * 2 + 1;
right = root * 2 + 2;
}
else{
break;
}
}
}
//小堆
//void _AdjustUp(int child){
// while (1){
// int root = (child - 1) / 2;
// if (_array[root]>_array[child]){
// swap(_array[root], _array[child]);
// child = root;
// }
// else {
// break;
// }
// if (root == 0){
// break;
// }
// }
//}
//大堆
void _AdjustUp(int child){
while (1){
int root = (child - 1) / 2;
if (_array[root] < _array[child]){
swap(_array[root], _array[child]);
child = root;
}
else {
break;
}
if (root == 0){
break;
}
}
}
private:
vector<T> _array;
};
void Test1()
{
int array[10] = { 10, 16, 18, 12, 11, 13, 15, 17, 14, 19 };
Heap<int> hp1(array, 10);
hp1.Display();
hp1.insert(-1);
hp1.Display();
hp1.MoveHeap();
hp1.Display();
}
int main()
{
Test1();
system("pause");
return 0;
}
小堆
大堆