堆排序 图解 (网上摘抄)(方便查询)
来源:互联网 发布:内蒙古大数据 编辑:程序博客网 时间:2024/05/16 19:12
数据结构中的堆和操作系统中的堆、堆栈(栈)是没有关系的,大家不要像我一样有误解。
数据结构中的堆分两种:大(顶)堆和小(顶)堆,简单来说就是
〇 。
O O O O
。 。 。 。 (大堆) 〇 〇 〇 〇(小堆)这个意思。
一般用二叉树来描述这种数据结构,存储可以用数组。
下面是排序思路:
(图):
C++代码:
- #include <iostream>
- #include <algorithm>
- using std::cout;
- using std::cin;
- using std::endl;
- template<class T>
- class Out{
- public:
- void operator()(T o)
- {
- cout<<o<<'\t';
- }
- };
- template<class T>
- void Swap(T& a,T&b)
- {
- T t=a;
- a=b;
- b=t;
- }
- inline int Rt(int idx)
- {
- return (idx<<1)+2;
- }
- inline int Lt(int idx)
- {
- return (idx<<1)+1;
- }
- template<class T>
- void HeapBuild(T* A,int idx,int size)
- {
- int child;
- for(;idx<=size/2;idx=child)
- {
- child=Lt(idx);
- if (child<size&&A[child]>A[idx])
- {
- Swap(A[idx],A[child]);
- }
- child=Rt(idx);
- if (child<size&&A[child]>A[idx])
- {
- Swap(A[idx],A[child]);
- }
- }
- }
- template<class T>
- void HeapSort(T* A,int size)
- {
- for (int i=size/2;i>=0;i--)
- {
- HeapBuild(A,i,size);
- }
- for (int i=size-1;i>=0;i--)
- {
- Swap(A[0],A[i]);
- HeapBuild(A,0,i);
- }
- }
- int main()
- {
- int size=0;
- cout<<"enter elements count num:"<<endl;
- cin>>size;
- int* elems = new int[size];
- cout<<"Input all elements to be sort:"<<endl;
- for(int i=0;i<size;cin>>elems[i++]);
- HeapSort(elems,size);
- std::for_each(elems,elems+size,Out<int>());
- delete []elems;
- }
0 0
- 堆排序 图解 (网上摘抄)(方便查询)
- Fopen 函数 C语言 (网上摘抄)(方便查询)
- C语言: fwrite和fread函数的用法小结 (网上摘抄,方便以后查询)
- C++ 控制台窗口隐藏及其代码 【网上摘抄,方便查询】
- C++ 文件输入输出基础 【网上摘抄,方便查询】
- C++程序运行时间计算【网上摘抄,方便查询】
- GetAsyncKeyState 函数 上下左右键 回车键等的判断【网上摘抄,方便查询】
- 堆排序——深入浅出(图解)
- TOMCAT启动(原版网上摘抄)
- (转)网上摘抄:图像处理的网上资料
- 懒人摘抄(内容转自CSDN资源中教程)-数据查询03-排序查询
- 堆排序原理图解
- 堆排序原理图解
- 堆排序原理图解
- 图解堆排序
- 图解堆排序
- 堆(堆排序)
- SSH反向代理相关介绍(网上摘抄+修改)
- iOS:Objective-C字面量
- 【bzoj4538】【HNOI2016】【网络】【树链剖分+线段树套堆】
- Struts2基础
- zepto商城顶部分类导航下拉菜单代码
- mysql语句
- 堆排序 图解 (网上摘抄)(方便查询)
- 如何修改element.style样式
- Oracle-存储过程与函数
- 微信营销大时代,如何实现传播力与用户量的双提升?
- android5.0之Activity过渡动画
- 【leetcode】242. Valid Anagram
- B00013 字符串哈希函数
- 程序锁的看门狗
- C# Json序列化工具--Newtonsoft.Json简介和使用