代码实现
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
typedef class Heap
{
public:
Heap()//构造
{
_a = nullptr;
_capacity = _size = 0;
}
Heap(Heap& p)
{
// 复制大小和容量
_size = p._size;
_capacity = p._capacity;
// 分配新的内存
_a = new int[_capacity];
// 复制原对象的数据
for (int i = 0; i < _size; ++i) {
_a[i] = p._a[i];
}
}
~Heap()//析构
{
delete []_a;
_capacity = _size = 0;
}
Heap& operator=(const Heap& p)
{
if (this != &p)
{
delete[] _a;
_size = p._size;
_capacity = p._capacity;
_a = new int[_capacity];
for (int i = 0;i < _size;i++)
{
_a[i] = p._a[i];
}
}
return *this;
}
void Swap1(int* p1,int* p2)//交换两个数据
{
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void AdjustUp(int child)//向上调整
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (_a[child] < _a[parent])
{
Swap1(&_a[child], &_a[parent]);
child = parent;
parent = (parent - 1) / 2;
}
else
{
break;
}
}
}
void HPPush(int x)//插入
{
if (_size == _capacity)
{
int newcapacity = _capacity == 0 ? 4 : _capacity * 2;
_capacity = newcapacity;
int* tmp = new int[_capacity];
for (int i = 0;i < _size;i++)
{
tmp[i] = _a[i];
}
delete[] _a; // 释放原内存
_a = tmp;
}
_a[_size] = x;
_size++;
AdjustUp(_size - 1);
}
int HPTop()//取堆顶元素
{
return _a[0];
}
void AdjustDown(int n, int parent)//向下调整
{
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && _a[child+1] < _a[child])
{
++child;
}
if (_a[child] < _a[parent])
{
Swap1(&_a[child], &_a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HPPop()//删除堆顶元素
{
assert(_size > 0);
Swap1(&_a[0], &_a[_size - 1]);
_size--;
AdjustDown(_size, 0);
//先进行堆尾堆顶交换,再进行重新成堆排序,不改变堆结构
}
int size()
{
return _size;
}
int capacity()
{
return _capacity;
}
bool HPEmpty()
{
return _size == 0;
}
private:
int* _a;
int _size;
int _capacity;
};
测试代码
#include"myhp.h"
void hp_test1()
{
Heap hp;
hp.HPPush(10);
hp.HPPush(9);
hp.HPPush(8);
hp.HPPush(7);
hp.HPPush(6);
hp.HPPush(5);
}
void hp_test2()
{
Heap hp;
hp.HPPush(10);
hp.HPPush(9);
hp.HPPush(8);
hp.HPPush(7);
hp.HPPush(6);
hp.HPPush(5);
while (!hp.HPEmpty())
{
cout << hp.HPTop() << ' ';
hp.HPPop();
}
}
int main()
{
hp_test2();
return 0;
}
运行结果