堆排序是一种效率很高的排序方法,尤其是在大量数据排序方面。
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;
}
}
}
};