Commit 0d2555a3 authored by CDK6182CHR's avatar CDK6182CHR
Browse files

2021.6.17 maxheap

parent 64426a6c
......@@ -109,4 +109,112 @@ void MinHeap<T>::pop()
throw "EMPTY HEAP";
data[0] = std::move(data[--size]); //直接覆盖!
sift_down(0);
}
\ No newline at end of file
}
/// <summary>
/// 具有固定最大长度的最大堆
/// (暴力把小于改成大于实现)
/// </summary>
template <typename T>
class MaxHeap {
const int max_size;
T* data;
int size;
public:
MaxHeap(int size_);
~MaxHeap()noexcept;
void push(const T& t);
void emplace(T&& t);
void pop();
inline const T& top()const {
return data[0];
}
inline T& top() {
return data[0];
}
inline bool empty()const {
return size == 0;
}
private:
void sift_down(int start);
void sift_up(int start);
};
template<typename T>
MaxHeap<T>::MaxHeap(int size_) :max_size(size_), size(0)
{
data = new T[max_size];
}
template<typename T>
MaxHeap<T>::~MaxHeap()noexcept
{
if (data) {
delete[]data;
data = nullptr;
}
}
template<typename T>
void MaxHeap<T>::sift_down(int start)
{
int i = start;
int ch = 2 * i + 1; //指向子女中最大的那个
while (ch < size) {
if (ch + 1 < size && data[ch + 1] > data[ch]) {
ch++;
}
if (data[ch] > data[i]) {
std::swap(data[ch], data[i]);
i = ch;
ch = 2 * i + 1;
}
else break;
}
}
template<typename T>
void MaxHeap<T>::sift_up(int start)
{
int i = start; //int div 指向父节点
while (i > 0) {
int par = (i - 1) / 2;
if (data[i] > data[par]) {
std::swap(data[i], data[par]);
i = par;
}
else break;
}
}
template<typename T>
void MaxHeap<T>::emplace(T&& t)
{
if (size >= max_size)
throw "OVERFLOWED";
data[size++] = std::move(t);
sift_up(size - 1);
}
template<typename T>
void MaxHeap<T>::push(const T& t)
{
if (size >= max_size)
throw "OVERFLOWED";
data[size++] = t;
sift_up(size - 1);
}
template<typename T>
void MaxHeap<T>::pop()
{
if (size <= 0)
throw "EMPTY HEAP";
data[0] = std::move(data[--size]); //直接覆盖!
sift_down(0);
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment