数据结构中最大值堆C++实现

包含建堆 插入 删除最大值


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


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值