堆(Heap)可以视为完全二叉树
它的数据结构就是数组对象,在堆中,都是以下标进行访问的。
堆分为:
最大堆:每个父节点的都大于孩子节点。
最小堆:每个父节点的都小于孩子节点。
如果有组数据:int a [] = {10,11, 13, 12, 16, 18, 15, 17, 14, 19};
构建成大堆:
创建成小堆:
因为大堆和小堆代码大致差不多,所以可以进行复用,这里就用到了仿函数。
我用的代码是大堆,但是我想创建小堆时,直接将
代码:
Heap.h
#pragma once
#include <vector>
template <class T>
struct Less
{
bool operator()(const T&l, const T&r) const
{
return l < r;
}
};
template <class T>
struct Greater
{
bool operator()(const T&l, const T&r) const
{
return l > r;
}
};
//大堆
template <class T, class Compare = Greater<T>>
class Heap
{
public:
Heap()//无参构造函数
{}
Heap(T* a, size_t n)//构造函数
{
_a.reserve(n);
for (size_t i = 0; i < n; i++)
{
_a.push_back(a[i]);
}
for (int i = (_a.size() - 2) / 2; i >= 0; i--)
{
_AdjustDown(i);
}
}
void Push(const T& x)//插入数据
{
_a.push_back(x);
_AdjustUp(_a.size() - 1);
}
void Pop()//删除数据
{
assert(!_a.empty());
swap(_a[0], _a[_a.size() - 1]);
_a.pop_back();
_AdjustDown(0);
}
const T& Top() const
{
return _a[0];
}
protected:
void _AdjustDown(int root)//向下调整算法用于创建堆
{
Compare comFunc;
int parent = root;
int child = root * 2 + 1;
while (child < _a.size())
{
if ((child+1<_a.size()) && comFunc(_a[child + 1],_a[child]))
{
++child;
}
//到这里了,在大堆里child就是最大的那个孩子,小堆相反
if (child<_a.size() && comFunc(_a[child] ,_a[parent]))//大堆里,孩子比父亲大
{
swap(_a[child], _a[parent]);//交换
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void _AdjustUp(int child)//向上调整算法用于插入数据
{
Compare comFunc;
int parent = (child - 1) / 2;
while (child > 0)
{
if (comFunc(_a[child] , _a[parent]))
{
swap(_a[child], _a[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
protected:
vector<T> _a;
};
void TestHeap()
{
int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
Heap<int> hp1(a, sizeof(a) / sizeof(a[0]));
hp1.Push(34);
hp1.Pop();
}
Test.cpp
#include <iostream>
#include <assert.h>
using namespace std;
#include "Heap.h"
int main()
{
TestHeap();
return 0;
}

6944

被折叠的 条评论
为什么被折叠?



