最小堆的数组实现

#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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值