堆排序是一个不稳定的排序算法,其时间复杂度为O(nlgn),空间复杂度为O(1)。其基本思想是对数组建立一个初始堆,然后进行一系列的交换和调整,最后得到需要的有序序列。
堆排序的一种实现:
template <typename T>
void Adjust(T *array, int parent, int size) //调整函数
{
assert(NULL != array && parent >= 0);
int child = 2*parent + 1;
while(child < size)
{
if(child+1 < size)
child = Greater<int>()(array[child], array[child+1]) ? child : child+1;
if(Greater<T>()(array[child], array[parent]))
swap(array[parent], array[child]);
else
break;
parent = child;
child = 2*parent + 1;
}
}
template <typename T>
void HeapSort(T *array, int size)
{
assert(NULL != array && size > 0);
if(size == 1)
return;
for(int i = ((size-2)>>1); i >= 0; i--) //建立初始堆
Adjust(array, i, size);
while(size > 1) //进行交换和调整
{
swap(array[0], array[size-1]);
size--;
Adjust(array, 0, size);
}
}
测试函数:
void test5()
{
int arr[100] = { 0 };
int sz = sizeof(arr) / sizeof(arr[0]);
srand((unsigned int)time(0));
for(int i = 0; i < sz; i++) //Assign values with random numbers
{
arr[i] = rand() % sz;
}
for(int i = 0; i < sz; i++) //print array
cout << arr[i] << " ";
cout << endl << endl << endl << "sort:" << endl;
HeapSort(arr, sz); //sort
for(int i = 0; i < sz; i++) //print array
cout << arr[i] << " ";
cout << endl;
for(int i = 1; i < sz; i++) //check that the sort is correct
{
if(Less<int>()(arr[i], arr[i-1]))
cout << "sort error! " << i << endl;
}
}
程序运行结果: