最小堆实现

#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>

using namespace std;

template <typename Comparable>
class BinaryHeap{
public:

	BinaryHeap (const vector<Comparable> &s):element(s) {
		MaxIndex=maxIndex();
		printCurrentState();
		buildHeap();
	}

	bool isEmpty(){
		return element.size()<=1;
	}

	void insert(Comparable value){
		element.push_back(value); //insert a value
		++MaxIndex;
		percolateUp();            //build the heap
	}

	void deleteMin(Comparable &s){
		if(isEmpty())
			return;
		s=element[1];
		element[1]=element[MaxIndex];
		element.pop_back();
		--MaxIndex;
		if(!isEmpty())
			percolateDown(1);
	}
private:
	vector<Comparable> element;
	int MaxIndex;

	void buildHeap(){
		for(int i=MaxIndex/2;i>0;--i){
			percolateDown(i);
		}
	}

	int maxIndex(){
		return element.size()-1;
	}
	void percolateDown(int index){
		Comparable tmp=element[index];
		int childIndex;
		for(;index*2<=MaxIndex;index=childIndex){
			childIndex=2*index;
			if(childIndex<MaxIndex&& element[childIndex]>element[childIndex+1])
				++childIndex;

			if(element[childIndex]<tmp)
				element[index]=element[childIndex];
			else
				break;
		}

		element[index]=tmp;
	//	printCurrentState();
	}

	void printCurrentState(){
		for(int i=1;i<=MaxIndex;++i)
			cout<<element[i]<<" ";
		cout<<endl;
		for(int i=1;i<=MaxIndex;++i)
			cout<<i<<" ";
		cout<<endl;
		cout<<endl;
		cout<<endl;
	}
	void percolateUp(){
		int hole=MaxIndex;
		Comparable tmp=element[hole];
		int parent;
		for(;hole/2>0;hole=parent){
			parent=hole/2;
			if(element[parent]>tmp)
				element[hole]=element[parent];
			else
				break;
		}
		element[hole]=tmp;
	}
};

int main(){
	srand((unsigned)time(0));
	vector<int> s;

	for (int i=0;i<10;++i){
		s.push_back(rand()%10);
		cout<<s[i]<<" ";
	}
	cout<<endl;

	BinaryHeap<int> heap(s);
	//heap.insert(5);

	while(!heap.isEmpty()){
		int s=-100;
		heap.deleteMin(s);
		cout<<s<<" ";
	}
	cout<<endl;
	system("pause");
}


还没理解透彻就编了,最终花了很多时间找问题出在哪里

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值