最大堆和堆排序

#pragma once
#ifndef _MAXHEAP_H_
#define _MAXHEAP_H_
#define DefaultSize 10
template <class T>
class MaxHeap
{
public:
	MaxHeap(int sz=DefaultSize)
	{
		maxHeapSize=(sz>DefaultSize) ? sz : DefaultSize;
		heap=new T[maxHeapSize];
		if(heap==NULL) exit(1);
		currentSize=0;
	}
	MaxHeap(int arr[], int n)
	{
		maxHeapSize=(n>DefaultSize) ? n : DefaultSize;
		heap=new T[maxHeapSize];
		if(heap==NULL) exit(1);
		for(int i=0; i<n; ++i) heap[i]=arr[i];
		currentSize=n;
		int currentPos=(currentSize-2)/2;
		while(currentPos>=0)
		{
			siftDown(currentPos, currentSize-1);
			currentPos--;
		}
	}
	~MaxHeap() {delete [] heap;}
	bool Insert(const T& x)
	{
		if(currentSize=maxHeapSize) return false;
		heap[currentSize]=x;
		siftUp(currentSize);
		currentSize++;
		return true;
	}
	bool Remove(T& x)
	{
		if(!currentSize) return false;
		x=heap[0];
		heap[0]=heap[currentSize-1];
		currentSize--;
		siftDown(0, currentSize-1);
		return true;
	}
	bool IsEmpty() const {return currentSize==0;}
	bool IsFull() const {return currentSize==maxHeapSize;}
	void MakeEmpty() {currentSize=0;}
	void HeapSort()
	{
		for(int i=currentSize-1; i>=0; i--)
		{
			T temp=heap[0]; heap[0]=heap[i]; heap[i]=temp;
			siftDown(0, i-1);
		}
	}
private:
	void siftDown(const int start, const int m)
	{
		int i=start; int j=2*i+1;
		T temp=heap[i];
		while(j<=m)
		{
			if(j<m&&heap[j]<heap[j+1]) j++;
			if(temp>=heap[j]) break;
			else
			{
				heap[i]=heap[j];
				i=j; j=2*j+1;
			}
		}
		heap[i]=temp;
	}
	void siftUp(int start)
	{
		int j=start, i=(j-1)/2;
		T temp=heap[j];
		while(j>0)
		{
			if(heap[i]<temp) {heap[j]=heap[i]; j=i; i=(j-1)/2;}
			else break;
		}
		heap[j]=temp;
	}
private:
	T *heap;
	int currentSize;
	int maxHeapSize;
};
#endif

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值