码迷,mamicode.com
首页 > 编程语言 > 详细

C++动态数组简单模拟二叉堆

时间:2015-06-11 11:06:35      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

//C++动态数组简单模拟二叉堆
#include<iostream>

using namespace std;

class BinaryHeap
{
private:
	int cap;  //数组最大容量
	int size; //当前元素个数
	int* datas; //数组首地址
public:
	explicit BinaryHeap(int cap_) :cap(cap_), size(0)
	{
		datas = new int[cap];
	}
	~BinaryHeap(){ delete datas; }
	void Insert(int);
	int DeleteMin();
};

//用数组表示的树,当下标从0开始时,i为当前节点,i*2+1为i的左子树节点,i*2+2为i的右子树节点,i/2为i的父节点

void BinaryHeap::Insert(int data)
{
	int i;
	for (i = size; i / 2 >= 0 && datas[i / 2] > data; i /= 2) //上滤
	{
		datas[i] = datas[i / 2];
	}
	datas[i] = data;
	size++;
}

int BinaryHeap::DeleteMin()
{
	int i = 0, child = 0;
	int lastdata = datas[--size];
	int mindata = datas[0];
	for (i = 0; i * 2 + 1 <= size-1; i = child)   //下滤
	{
		child = i * 2 + 1;
		if (child < size-1 && datas[child + 1] < datas[child])
		{
			child++;
		}
		if (lastdata > datas[child])
		{
			datas[i] = datas[child];
		}
		else
		{
			break;
		}
	}
	datas[i] = lastdata;
	return mindata;
}

int main()
{
	BinaryHeap t(400);

	for (int i = 0; i < 100; i++)
		t.Insert(i);
	for (int i = 200; i > 100; i--)
		t.Insert(i);


	for (int i = 0; i < 200; i++)
		cout << t.DeleteMin() << endl;


	cin.get();
	return 0;
}

C++动态数组简单模拟二叉堆

标签:

原文地址:http://blog.csdn.net/linukey/article/details/46454105

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!