#pragma once
#include<iostream>
#include<vector>
using namespace std;
//仿函数定义。
template<class T>
struct Big
{
bool operator()(T x, T y)
return x > y;
};
template<class T>
struct Sma
{
bool operator()(T x, T y)
return x < y;
};
//建堆的向下调整过程
template<class T, template<class> class Cmp>
void AdjustDown(T* arr, size_t end, int root)
{
if (end <= 1)
return;
while (root <= (end - 2) / 2)
{
int child = root * 2 + 1;
//找到
if (child + 1 < end && Cmp<T>()(arr[child] ,arr[child+1]))
{
child++;
}
Cmp<T>()(arr[root] ,arr[child]) ? swap(arr[root], arr[child]):(1);
root = child;
}
}
//堆排定义,template<class> class typeName 定义类模板依赖。调用处就不用传入类型
template<class T,template<class> class Cmp = Big>
void HeapSort(T *arr,size_t size)
{
//建堆
int root = (size - 2) / 2;
while (root >= 0)
{
AdjustDown<T,Cmp>(arr, size, root);
root--;
}
//排序
int end = size - 1;
while (end > 0)
{
swap(arr[0], arr[end]);
AdjustDown<T,Cmp>(arr, end, 0);
end--;
}
}
void TestHeapSort()
{
int arr[] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
int arr1[] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
HeapSort<int, Sma>(arr, 10);
HeapSort<int, Big>(arr1, 10);
}