堆排序的实现
来源:互联网 发布:ucosiii软件定时器 编辑:程序博客网 时间:2024/05/01 21:43
堆排序c++实现
//大堆比较
template<class T>
bool max_compare(T a, T b)
{
return a < b;
}
//小堆比较
template<class T>
bool min_compare(T a, T b)
{
return a > b;
}
template<class T>
void heapify(T *src, int start,int len,bool (*compare)(T ,T ))
{
int left = (start + 1)*2 - 1;
int right = left + 1;
int temp = start;
while (true)
{
if (left<len && compare(src[temp] , src[left]))
temp = left;
if (right<len && compare(src[temp] , src[right]))
temp = right;
if (start == temp)
break;
swap(src[start], src[temp]);
start = temp;
left = (start+1)*2 - 1;
right = left + 1;
}
}
template<class T>
void build_heap(T* src, int len, bool(*compare)(T, T))
{
int i;
for (i = (len/2)-1; i >= 0; i--)
heapify(src, i, len, compare);
}
template<class T>
void sort_head(T* src, int len, bool(*compare)(T, T))
{
assert(len > 0);
build_heap(src, len, compare);
while (len > 0)
{
swap(src[0], src[--len]);
heapify(src, 0, len, compare);
}
}
void test_heap()
{
int a[] = { 5, 4, 8, 2, 1, 12 };
sort_head(a, 6, min_compare);
for (int i = 0; i < 6; i++)
cout << a[i] << ",";
cout << endl;
}
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 堆排序的实现
- 数据库--并发控制
- hadoop正式学习之redis---网络数据爬虫
- HDU 1269 迷宫城堡 简单求连通块
- activiti 无法将名称 'extension' 解析为 'element declaration' 组件
- gzip: stdin: not in gzip format 解决办法
- 堆排序的实现
- Linux如何打开关闭端口及终止进程的方式
- HDOJ(HDU) 2164 Rock, Paper, or Scissors?
- iOS开发技巧系列 使用Swift反射
- APIO2016游记
- 屏幕适配全攻略
- NYIST 714 异 形 卵(第六届河南省程序设计大赛)
- 比赛排名--拓扑排序
- Java中使用Jedis操作Redis