void _AdjustDown(int root,int size)
{
Camper camper; //仿函数
int parent = root;
int child = parent * 2 + 1;
while (child <= size) //保证访问不越界
{
if (child < size && camper(_vec[child+1] , _vec[child])) //保证存在右子树、同时判断右子树是否大于或小于左子树
{
child++;
}
if (camper(_vec[child], _vec[parent]))
{
swap(_vec[parent], _vec[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void Sort()
{
size_t size = _vec.size(); //数据数量
while (size > 1)
{
swap(_vec[0], _vec[size - 1]);
size--;
_AdjustDown(size);
}
}
template<class T>
struct Greater //大于
{
bool operator ()(const T& l, const T& p)
{
return l > p;
}
};
template<class T>
struct Less //小于
{
bool operator () (const T&l, const T& p)
{
return l < p;
}
};
#include<iostream>
using namespace std;
#include<vector>
template<class T>
struct Greater //大于
{
bool operator ()(const T& l, const T& p)
{
return l > p;
}
};
template<class T>
struct Less //小于
{
bool operator () (const T&l, const T& p)
{
return l < p;
}
};
template<class T,class Camper>
class HeapSort //建大堆
{
public:
HeapSort()
{}
HeapSort(T* arr, size_t n)
{
_vec.reserve(n);
if (arr != NULL)
{
for (size_t i = 0; i < n; i++)
{
_vec.push_back(arr[i]);
}
}
_AdjustDown(_vec.size());
}
void Sort()
{
size_t size = _vec.size(); //数据数量
while (size > 1)
{
swap(_vec[0], _vec[size - 1]);
size--;
_AdjustDown(size);
}
}
void Print()
{
for (size_t i = 0; i < _vec.size(); i++)
{
cout << _vec[i] <<" ";
}
cout << endl;
}
protected:
void _AdjustDown(int size)
{
int parent = (size - 2) / 2;
while (parent >= 0)
{
_AdjustDown(parent, size - 1);
parent--;
}
}
void _AdjustDown(int root,int size)
{
Camper camper; //仿函数
int parent = root;
int child = parent * 2 + 1;
while (child <= size) //保证访问不越界
{
if (child < size && camper(_vec[child+1] , _vec[child])) //保证存在右子树、同时判断右子树是否大于或小于左子树
{
child++;
}
if (camper(_vec[child], _vec[parent]))
{
swap(_vec[parent], _vec[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
private:
vector<T> _vec;
};
void TextSort()
{
int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
HeapSort<int,Greater<int>> h(a, sizeof(a) / sizeof(a[0]));
h.Print();
h.Sort();
h.Print();
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有