堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
#pragma once
#include<vector>
#include<assert.h>
template<class T>
class Heap
{
public:
Heap()
:_a(NULL)
{}
Heap(const T* a, int size)
{
_a.reserve(size);
for (int i = 0; i < size; i++)
{
_a.push_back(a[i]);
}
size_t parent = (size - 2) / 2;
for (int i = (_a.size() - 2) / 2; i >= 0; --i)
{
_AdjustDown(i, size);
}
}
~Heap()
{}
//堆排序
//将数据从小到大输出,
void HeapSort(T* a,int size)
{
while (size > 1)
{
swap(_a[0], _a[size - 1]);
size--;
_AdjustDown(0, size);
}
}
void Print( size_t size)
{
for (int i = 0; i < size; i++)
{
cout << _a[i] << " ";
}
cout << endl;
}
protected:
void _AdjustDown(size_t parent, size_t size)
{
size_t child = parent * 2 + 1;
while (child<size)
{
if (child + 1<size &&_a[child]<_a[child + 1])
{
++child;
}
if (_a[child] > _a[parent])
{
swap(_a[child], _a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
break;
}
}
protected:
vector<T> _a;
};
void Test()
{
int array[] = { 10, 11, 13, 12, 19,16, 18, 15, 17, 14 };
Heap<int> hp1(array, sizeof(array) / sizeof(array[0]));
hp1.HeapSort(array, sizeof(array) / sizeof(array[0]));
hp1.Print(sizeof(array) / sizeof(array[0]));
}
//堆排序
#include<iostream>
using namespace std;
#include<assert.h>
void AdjustDown(int* a, size_t size, size_t parent)
{
int child = parent * 2 + 1; //给出父节点可以求出子节点,parent*2+1
while (child < size)//不能等于,child=*2+1,可能等于size
{
if (child + 1 < size && a[child + 1] > a[child])//比较左右孩子那个大
{
++child;//如果a[child+1]大,下标++,指向child+1
}
if (a[child] > a[parent]) //如果子节点比父节点大,就交换,父节点变为大的
{
swap(a[child], a[parent]);
parent = child;//向下继续调整,child赋值给parent
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int* a, size_t size)
{
assert(a);
// 建堆 N*Lg(N)
for (int i = (size - 2) / 2; i >= 0; --i) //从父节点开始进行调整
{//i-1为最后一个元素下标,在减一除以2求出父节点的下标
AdjustDown(a, size, i);//
}
for (int i = 0; i < size; ++i)
{
swap(a[0], a[size - 1 - i]);//此时a[0]存放最大数字,和最后进行交换
//最大的就跑到最后面,再以0为父节点,size-1-i个数据进行调整。
AdjustDown(a, size - 1 - i, 0);
}
}
void PrintArray(int* a, int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void TestHeapSort()
{
//int a[] = { 2, 5, 4, 6, 8, 0 };
int a[] = { 2, 5, 4, 9, 3, 6, 8, 7, 1, 0 };
HeapSort(a, sizeof(a) / sizeof(a[0]));
PrintArray(a, sizeof(a) / sizeof(a[0]));
}
int main()
{
TestHeapSort();
system("pause");
return 0;
}