堆排序 图解 (网上摘抄)(方便查询)

数据结构中的堆和操作系统中的堆、堆栈(栈)是没有关系的,大家不要像我一样有误解。

数据结构中的堆分两种:大(顶)堆和小(顶)堆,简单来说就是

              〇                                                        。

      O                 O                                    O              O    

。         。   。         。    (大堆) 〇         〇    〇         〇(小堆)这个意思。

一般用二叉树来描述这种数据结构,存储可以用数组。

下面是排序思路:

(图):



C++代码:

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <algorithm>  
  3.   
  4. using std::cout;  
  5. using std::cin;  
  6. using std::endl;  
  7. template<class T>  
  8. class Out{  
  9. public:  
  10.     void operator()(T o)  
  11.     {  
  12.         cout<<o<<'\t';  
  13.     }  
  14. };  
  15. template<class T>  
  16. void Swap(T& a,T&b)  
  17. {  
  18.     T t=a;  
  19.     a=b;  
  20.     b=t;  
  21. }  
  22. inline int Rt(int idx)  
  23. {  
  24.     return (idx<<1)+2;  
  25. }  
  26. inline int Lt(int idx)  
  27. {  
  28.     return (idx<<1)+1;  
  29. }  
  30.   
  31. template<class T>  
  32. void HeapBuild(T* A,int idx,int size)  
  33. {  
  34.     int child;  
  35.     for(;idx<=size/2;idx=child)  
  36.     {  
  37.         child=Lt(idx);  
  38.         if (child<size&&A[child]>A[idx])  
  39.         {  
  40.             Swap(A[idx],A[child]);  
  41.         }  
  42.         child=Rt(idx);  
  43.         if (child<size&&A[child]>A[idx])  
  44.         {  
  45.             Swap(A[idx],A[child]);  
  46.         }  
  47.     }  
  48. }  
  49. template<class T>  
  50. void HeapSort(T* A,int size)  
  51. {  
  52.     for (int i=size/2;i>=0;i--)  
  53.     {  
  54.         HeapBuild(A,i,size);  
  55.     }  
  56.     for (int i=size-1;i>=0;i--)  
  57.     {  
  58.         Swap(A[0],A[i]);  
  59.         HeapBuild(A,0,i);  
  60.     }  
  61. }  
  62. int main()  
  63. {  
  64.     int size=0;  
  65.     cout<<"enter elements count num:"<<endl;  
  66.     cin>>size;  
  67.     int* elems = new int[size];  
  68.     cout<<"Input all elements to be sort:"<<endl;  
  69.     for(int i=0;i<size;cin>>elems[i++]);  
  70.     HeapSort(elems,size);  
  71.     std::for_each(elems,elems+size,Out<int>());  
  72.     delete []elems;  
  73. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值