堆排C++实现

template <class Type>
void HeapAdjust(Type* heap, size_t begin, size_t end, bool (*cmp)(const Type&,const Type&))
{
	for (size_t i = begin; i <= (end / 2);)
	{
		size_t exp = 0;
		if(i * 2 < end && cmp(heap[i * 2 - 1], heap[i * 2]))
			exp = 1;
		if (cmp(heap[i - 1], heap[i * 2 + exp - 1]))
		{
			swap(heap[i - 1], heap[i * 2 + exp - 1]);
			i = i * 2 + exp;
		}
		else
			break;
	}
}

template <class Type>
void  HeapSort(Type* heap, size_t length, bool (*cmp)(const Type&, const Type&))
{
	for (size_t i = length / 2; i >= 1; i--)
		HeapAdjust(heap, i, length, cmp);
	for (size_t index = length; index > 1; index--)
	{
		swap(heap[0], heap[index - 1]);
		HeapAdjust(heap, 1, index - 1, cmp);
	}
}


bool cmp(const int& a, const int& b)
{
	return (a <= b) ? true : false;
}

int main()
{
	int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
	HeapSort(a, 9, cmp);
	return 0;
}

原文链接: https://www.cnblogs.com/ltang/archive/2010/10/26/1861252.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    堆排C++实现

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/16584

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午4:56
下一篇 2023年2月7日 下午4:57

相关推荐