堆排序

 #include <iostream>
 #include <vector>
using namespace std;
template <class T>
class Heap
{
public:
	Heap()
	{}
	Heap(const T* array, size_t size){
		for (size_t i = 0; i < size; i++){
			_array.push_back(array[i]);
			for (int being = _array.size() / 2 - 1; being >= 0; --being){
				_AdjustDown(being);
			}
		}
	}
	Heap(vector<T>& array){
		_array.swap(array);
		for (int being = _array.size() / 2 - 1; being >= 0; --being){
			_AdjustDown(being);
		}
	}
	void insert(const T& x){
		_array.push_back(x);
		_AdjustUp(_array.size() - 1);
	}
	void MoveHeap(){
		_array[0] = _array[_array.size() - 1];
		_array.pop_back();
		for (int being = _array.size() / 2 - 1; being >= 0; --being){
			_AdjustDown(being);
		}
	}
	void Display()
	{
		for (size_t i = 0; i < _array.size(); i++)
		{
			cout << _array[i] << " ";
		}
		cout << endl;
	}
	 
protected:
	//小堆
	//void _AdjustDown(int root){
	//	int left = root * 2 + 1;
	//	int right = left + 1;
	//	while (left<_array.size()){
	//				int min = left;
	//		if (right < _array.size() && _array[right] < _array[left]){
	//			min = right;
	//		}
	//		if (_array[min] < _array[root]){
	//			swap(_array[min], _array[root]);
	//			root = min;
	//			left = root * 2 + 1;
	//			right = root * 2 + 2;
	//		}
	//		else{
	//			break;
	//		}
	//	}
	//}
//大堆
	void _AdjustDown(int root){
		int left = root * 2 + 1;
		int right = left + 1;
		while (left<_array.size()){
			int max = left;
			if (right < _array.size() && _array[right] > _array[left]){
				max = right;
			}
			if (_array[max] > _array[root]){
				swap(_array[max], _array[root]);
				root = max;
				left = root * 2 + 1;
				right = root * 2 + 2;
			}
			else{
				break;
			}
		}
	}

	//小堆
	//void _AdjustUp(int child){
	//	while (1){
	//		int root = (child - 1) / 2;
	//		if (_array[root]>_array[child]){
	//			swap(_array[root], _array[child]);
	//			child = root;
	//		}
	//		else  {
	//			break;
	//		}
	//		if (root == 0){
	//			break;
	//		}
	//	}
	//}
	//大堆
	void _AdjustUp(int child){
		while (1){
			int root = (child - 1) / 2;
			if (_array[root] < _array[child]){
				swap(_array[root], _array[child]);
				child = root;
			}
			else  {
				break;
			}
			if (root == 0){
				break;
			}
		}
	}
private:
	vector<T> _array;

}; 
void Test1()
{
	int array[10] = { 10, 16, 18, 12, 11, 13, 15, 17, 14, 19 };

	Heap<int> hp1(array, 10);
	hp1.Display();
	hp1.insert(-1);
	hp1.Display();
	hp1.MoveHeap();
	hp1.Display();
}
 
int main()
{
	Test1();
	system("pause");
	return 0;
}

小堆

大堆


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值