2.21 堆排序

2️⃣1️⃣ 堆排序

😀 因为上节课学了堆,堆排序就是很简单的把数据放进堆,然后再取出来

#include <iostream>
#include <vector>
using namespace std;

class MaxHeap{
private:
	int* heapArray;
	int maxSize;
	int currentSize;

	void trickleUp(int);  //向上渗透
	void trickleDown(int);//向下渗透
public:
	MaxHeap(int mx=10);
	~MaxHeap();
	bool Ismpty();
	void Push(const int);
	void Pop();
	int Top()const;
};

MaxHeap::MaxHeap(int mx){
	if(mx<1)
		throw"max size must be >=1.";

	maxSize = mx;
	currentSize = 0;
	heapArray = new int [maxSize];
}

MaxHeap::~MaxHeap(){
	delete []heapArray;
}

bool MaxHeap::Ismpty(){
	return currentSize==0;
}

void MaxHeap::Push(const int x){
	if(currentSize == maxSize)
		throw"MaxHeap is full.";
	heapArray[currentSize] = x;
	trickleUp(currentSize++);
}

void MaxHeap::trickleUp(int index){
	int parent = (index-1)/2;
	int bottom = heapArray[index];
	while (index > 0 && bottom > heapArray[parent]){
		heapArray[index] = heapArray[parent];
		index = parent;
		parent = (parent-1)/2;
	}
	heapArray[index] = bottom;
}

int MaxHeap::Top()const{
	return heapArray[0];
}

void MaxHeap::Pop(){
	heapArray[0] = heapArray [--currentSize];
	trickleDown(0);
}

void MaxHeap::trickleDown(int index){
	int largerChild;
	int top = heapArray[index];
	while(index < currentSize/2)
	{
		int LeftChild = 2*index + 1;
		int RightChild = LeftChild + 1;
		if(RightChild < currentSize && heapArray[LeftChild] < heapArray[RightChild])
			largerChild = RightChild;
		else	largerChild = LeftChild;

		if(top >= heapArray[largerChild])
			break;
		else heapArray[index] = heapArray[largerChild];
		index = largerChild;
	}
	heapArray[index] = top;
}

int main(){
	MaxHeap h(100);
	vector<int> arr{62,3,90,27,33,8,12,9,43,66};
	for(int i=0; i!=arr.size(); i++)
		h.Push(arr[i]);
	for(int i=0; i!=arr.size(); i++){
		arr[i] = h.Top();
		h.Pop();
	}
	for(int i=0; i!=arr.size(); i++)
		cout << arr[i] << " ";
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值