和最小堆相比,只是比较条件改变,其他不变,思路一样
#include <iostream>
#include <cassert>
using namespace std;
const int DefaultSize = 1;
template <class T, class E>
class MaxHeap
{
public:
MaxHeap(int sz)
{
maxHeapSize = (DefaultSize < sz) ? sz : DefaultSize;
heap = new E[maxHeapSize + 1];
if (heap == NULL) { cerr << "堆分配失败!" << endl; exit(1); }
currentSize = 0;
}
MaxHeap(E arr[], int n)
{
maxHeapSize = (DefaultSize < n) ? n : DefaultSize;
heap = new E[maxHeapSize + 1];
if (heap == NULL) { cerr << "堆分配失败!" << endl; exit(1); }
for (int i = 0; i < n; i++) heap[i] = arr[i];
currentSize = n;
int currentPos = (currentSize - 2) / 2;
while (currentPos >= 0)
{
siftDown(currentPos, currentSize - 1);
currentPos--;
}
}
~MaxHeap() {
delete[]heap;
}
bool Insert(const E& x)
{
heap[currentSize] = x;
siftUp(currentSize);
currentSize++;
return true;
}
bool RemoveMin(E& x)
{
if (!currentSize) {
cout << "Heap empty" << endl;
return false;
}
x = heap[0];
heap[0] = heap[currentSize - 1];
currentSize--;
siftDown(0, currentSize - 1);
return true;
}
bool IsEmpty()const {
return currentSize == 0;
}
bool IsFull()const {
return currentSize == maxHeapSize;
}
void MakeEmpty() {
delete heap;
currentSize = 0;
}
void output() {
for (int i = 0; i < currentSize; i++)
cout << heap[i] << " ";
cout << endl;
}
private:
E* heap;
int currentSize;
int maxHeapSize;
void siftDown(int start, int m)
{
int i = start, j = 2 * i + 1;
E temp = heap[i];
while (j <= m)
{
if (j<m && heap[j]<heap[j + 1])
{
j++;
}
if (temp >= heap[j]) break;
else
{
heap[i] = heap[j];
i = j;
j = 2 * j + 1;
}
}
heap[i] = temp;
}
void siftUp(int start)
{
int j = start, i = (j - 1) / 2;
E temp = heap[j];
while (j > 0)
{
if (heap[i] >= temp) break;
else
{
heap[j] = heap[i];
j = i;
i = (i - 1) / 2;
}
}
heap[j] = temp;
}
};