二叉队列的实现

头文件:

/*
*A class for Minimum BinaryHeap
*writter:	flyaway
*Time:	2012.5.22
*description:
*	use the array to store data
*	This class provide public functions:
*	insert()
*	findMin()
* 	deleteMin()
*   isEmpty()
*   makeEmpty()
*/
#ifndef BinaryHeap_H
#define BinaryHeap_H

#include<iostream>
#include<vector>
using namespace std;
template< typename T >
class BinaryHeap
{
	public:
			explicit BinaryHeap(const int capacity = 100);
			explicit BinaryHeap(const vector< T > & item);
			bool isEmpty();
			T findMin() ;
			void insert(const T &k);
			void deleteMin();
			void makeEmpty();
			
	private:
			int currentsize;	//number of elements in heap
			vector< T > array;	//The heap array
			
			void buildHeap();
			void ShiftDown(int hole);
};

#endif
下面是具体的实现:

#include "BinaryHeap.h"
template< typename T >
BinaryHeap< T > ::BinaryHeap(const int capacity)
{
	currentsize = capacity;
	array.resize(capacity+10);
}



template< typename T >
BinaryHeap< T >::BinaryHeap(const vector< T > &item)
{
	int i;
	int n =  item.size();
	array.resize(n+1);
	currentsize = n;
	for(i = 0;i < n;++i)
	{
		array[i+1] = item[i];
	}
	buildHeap();
}


template< typename T >
void BinaryHeap< T > ::buildHeap()
{
	int i;
	for(i = currentsize/2;i >= 1;--i)
	{
		ShiftDown(i);
	}
}

template< typename T >
void BinaryHeap< T >::ShiftDown(int hole)
{
	T tmp = array[hole];
	int father = hole;
	int child ;
	for(;father * 2 <= currentsize;father = child)
	{
		//find the smller child
		child = father * 2; 
		if(child != currentsize && array[child] >  array[child+1])
		{
			child ++;
		}
		if(array[child] < tmp)
		{
			array[father] = array[child];
		}
		//find the right place and break out the loop
		else
		{
			break;
		}	
	}
	array[father] = tmp;
}




template< typename T >
T BinaryHeap< T >::findMin() 
{
	if(isEmpty())
	{
		cerr<<"Error! The Heap is empty!";
		exit(1);
	}
	else
	{
		return array[1];
	}
}


template< typename T >
bool BinaryHeap< T > ::isEmpty()
{
	return currentsize <= 0;
}

template< typename T >
void BinaryHeap< T > ::insert(const T &k)
{
	++currentsize;
	int father = currentsize/2;
	int child = currentsize;
	for(;father > 0 && array[father] > k;)
	{
		array[child] = array[father];
		child = father;
		father = child / 2; 
	}
	if(father == 0)
	{
		array[1] = k;
	}
	else
	{
		array[father] = k;
	}
}




template< typename T >
void BinaryHeap< T > ::deleteMin()
{
	array[1] = array[currentsize--];
	ShiftDown(1);
}



template< typename T >
void BinaryHeap< T >::makeEmpty()
{
	array.clear();
	currentsize = 0;
}

作者博客: 点击打开链接

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值