#include <iostream>
using namespace std;
#define Maxn 1010
class heapClass
{
private:
int heap[Maxn],len;
public:
heapClass():len(0)
{
}
bool isempty();
void push(int x);
int pop();
};
void heapClass::push(int x)
{ //在向堆中插入数值时,首先在堆的末尾插入该数值,然后不断向上提升
//直到没有大小颠倒为止
int i=len++;
while(i>0)
{
int p=(i-1)/2;
if(heap[p]<=x) break;
heap[i]=heap[p];
i=p;
}
heap[i]=x;
}
int heapClass::pop()
{
//从堆中删除最小值时,首先把堆的最后一个节点的数值复制到根节点
//并且删除最后一个节点,然后不断向下交换直到没有大小颠倒为止
int ret=heap[0];
int x=heap[--len];
int i=0;
while(i*2+1<len)
{
int lchd=i*2+1,rchd=i*2+2;
if(rchd<len&&heap[rchd]<heap[lchd]) lchd=rchd;
if(heap[lchd]>x) break;
heap[i]=heap[lchd];
i=lchd;
}
heap[i]=x;
return ret;
}
bool heapClass::isempty()
{
return len==0;
}
int main()
{
heapClass *heapObj=new heapClass();
heapObj->push(5);
heapObj->push(2);
heapObj->push(6);
heapObj->push(3);
heapObj->push(99);
heapObj->push(190);
heapObj->push(1);
while(!heapObj->isempty())
{
cout<<heapObj->pop()<<" ";
}
delete heapObj;
cout<<endl;
system("pause");
return 0;
}
#include<iostream>
#include<functional>
#include<queue>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >queGreater;//最小堆
priority_queue<int,vector<int>,less<int>>queLess;//最大堆
int a[10]={1,7,5,4,9,10,19,2,5,3};
for(int i=0;i<10;i++)
{
queGreater.push(a[i]);
queLess.push(a[i]);
}
while(!queGreater.empty())
{
cout<<queGreater.top()<<" ";
queGreater.pop();
}
cout<<endl;
while(!queLess.empty())
{
cout<<queLess.top()<<" ";
queLess.pop();
}
cout<<endl;
system("pause");
return 0;
}