包含建堆 插入 删除最大值
#include <iostream>
using namespace std;
class maxHeap
{
private:
int *Heap;
int size;
int n;
void siftdown(int);
public:
maxHeap(int *h, int num, int max):n(num),size(max)
{
Heap = h;
}
int heapsize() const
{
return n;
}
bool isLeaf(int pos) const
{
return (pos >= n/2 && (pos <n));
}
int leftchild(int pos) const
{
return 2*pos + 1;
}
int rightchild(int pos) const
{
return 2*pos + 2;
}
int parent(int pos) const
{
return (pos-1)/2;
}
bool insert(const int &);
bool removemax(int &);
bool remove(int,int&);
void buildHeap()
{
for (int i=n/2-1;i>=0;--i)
siftdown(i);
}
};
void maxHeap::siftdown(int pos)
{
while (!isLeaf(pos))
{
int max = leftchild(pos);
int rc = rightchild(pos);
if ((rc < n) && (Heap[max]<Heap[rc]))
max = rc;
if (!(Heap[pos] < Heap[max])) return;
int temp = Heap[pos];
Heap[pos] = Heap[max];
Heap[max] = temp;
pos = max;
}
}
bool maxHeap::insert(const int& val)
{
if (n>=size) return false;
int curr = n++;
Heap[curr] = val;
while ((curr !=0) && (Heap[curr] > Heap[parent(curr)]))
{
int temp = Heap[curr];
Heap[curr] = Heap[parent(curr)];
Heap[parent(curr)] = temp;
curr = parent(curr);
}
return true;
}
bool maxHeap::removemax(int &it)
{
if (n==0) return false;
int temp = Heap[0];
Heap[0] = Heap[--n];
Heap[n] = temp;
if (n!=0) siftdown(0);
it = Heap[n];
return true;
}
int main()
{
int *s = new int[20];
s[0] = 22;
s[1] = 312;
s[2] = 222;
s[3] = 2234;
s[4] = 212;
s[5] = 292;
maxHeap heap(s,6,20);
heap.buildHeap();
for (int i=0;i<6;++i)
cout<<s[i]<<" ";
cout<<endl;
heap.insert(3222);
for (int i=0;i<7;++i)
cout<<s[i]<<" ";
cout<<endl;
}