堆排序

堆排序是一种效率很高的排序方法,尤其是在大量数据排序方面。

1、降序序排列
  例如:将{10,16,18,12,11,13,15,17,14,19}按照降序排列。 首先要明白,如果要将一组数据按照降序排列,则我们要借助最小堆来实现。具体的方法如下:

首先将这组数据建成最小堆:


现在a[0]就是最小的元素,我们将a[0]与最后一个元素进行交换,然后再将前9个数建堆。

将a[0]与a[8]交换,如下图:

重复上述操作,直到a[0]与a[0]交换的时候就停止,这时就已经排好序了。

时间复杂度:
第一次建堆的时间复杂度:O(N*lgN)。
每次调整的时间复杂度是O(lgN),总共有N次,即:O(N*lgN);
所以:
堆排序的时间复度:O(N*lgN)

2、升序排列。
  同理,升序排列要借助于最大堆。

完整代码:
#pragma once
#include<cassert>
template<typename T>
struct UpOder
{
	bool operator()(const T& l,const T& r)    //升序
	{
		return l < r;
	}
};

template<typename T>            //降序
struct DownOder
{
	bool operator()(const T& l, const T& r)
	{
		return l>r;
	}
};

//默认堆排序是升序,可通过仿函数传递参数设置为降序
template<typename T,class Compare=UpOder<T>>
class HeapSort
{
public:
	HeapSort()
	{}
	void Sort(T* a, int size)
	{
		//建堆
		assert(a);
		for (int i = (size - 2) / 2; i >= 0; --i)
		{
			AdjustDown(a, i, size);
		}

		//堆排序
		while (size >1)   
		{
			swap(a[0],a[size-1]);
			--size;
			AdjustDown(a,0,size);			
		}
	}
protected:
	//下滑调整
	void AdjustDown(T* a,int root,int size)
	{
		assert(size>0);
		int parent = root;
		int child = parent * 2 + 1;
		while (child < size)
		{
			if ((child + 1) < size&&Compare()(a[child],a[child+1]))
				child++;
			if (Compare()(a[parent], a[child]))
			{
				swap(a[parent],a[child]);
				parent = child;
				child = parent * 2 + 1;
			}
			else
			{
				break;
			}
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值