堆排序原理图解

来源:互联网 发布:淘宝卖家店名怎么改 编辑:程序博客网 时间:2024/05/01 11:56

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

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

              〇                                                        。

      O                 O                                    O              O    

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

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

下面是排序思路:

(图):



C++代码:

[cpp] view plaincopyprint?
  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