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;
}