堆排序算法思路详解-创新互联

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

成都创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:做网站、网站制作、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的西安网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

堆排序算法思路详解

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

堆排序算法思路详解

   实现代码如下:

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


}
template  >
void adjustdown(int index, size_t size, vector&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  >
static void GetHeap(vector&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

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

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


文章名称:堆排序算法思路详解-创新互联
本文网址:http://pwwzsj.com/article/ddphoj.html