堆排序算法思路详解

    堆排序是一种常见的排序算法,其时间复杂度为O(logN),重要思想为建堆取极值,根据需求进行排序,如下图:

wKiom1cytEnhY-J0AAAfaiVgGAE014.png

    值得思考的是,二次建堆的过程中,实际上是没有必要将所有元素都进行下调,只需要将根进行下调:

wKioL1cyttHw4SW7AAAjsJvEbHc794.png

    实现代码如下:

template <class T>//建立仿函数模板满足排序需求
struct CompMax
{
	bool operator()(const T& a, const T& b)
	{
		return a > b;
	}
};
template <class T>
struct CompMin
{
	bool operator()(const T& a,const T& b)
	{
		return a < b;
	}
};
template <class T ,class Com = CompMax<T> >
static void HeapSort(vector<T>&list)
{
	size_t size = list.size();
	GetHeap<T>(list, size);
	swap(list[0], list[size - 1]);
	while (--size > 1)
	{
		adjustdown<T>(0, size, list);
		swap(list[0], list[size - 1]);
	}


}
template <class T,class Com = CompMax<T> >
void adjustdown(int index, size_t size, vector<T>&list)
{
	Com comp;
	size_t parent = index;
	size_t child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size)
			child = child = comp(list[child], list[child + 1]) ? child : child + 1;
		if (!comp(list[parent], list[child]))
		{
			std::swap(list[child], list[parent]);
			parent = child;
			child = parent * 2 + 1;

		}
		else
			break;
	}
}
template <class T ,class Com = CompMax<T> >
static void GetHeap(vector<int>&list, size_t size)
{
	size_t parent = (size - 2) / 2;
	int begin = parent;
	Com comp;
	while (begin >= 0)
	{
		size_t child = parent * 2 + 1;
		while (child<size)
		{
			if (child + 1<size)
				child = child = comp(list[child], list[child + 1]) ? child : child + 1;
			if (!comp(list[parent], list[child]))
			{
				swap(list[child], list[parent]);
				parent = child;
				child = parent * 2 + 1;

			}
			else
				break;
		}
		parent = --begin;
	}

}

    如有不足,希望指正,有疑问也希望提出

本文出自 “pawnsir的IT之路” 博客,请务必保留此出处http://10743407.blog.51cto.com/10733407/1772174

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值