堆排序

来源:互联网 发布:mssql备份数据库命令 编辑:程序博客网 时间:2024/06/03 21:21
堆排序是一种效率很高的排序方法,尤其是在大量数据排序方面。

1、降序序排列
  例如:将{10,16,18,12,11,13,15,17,14,19}按照降序排列。首先要明白,如果要将一组数据按照降序排列,则我们要借助最小堆来实现。具体的方法如下:

首先将这组数据建成最小堆:


现在a[0]就是最小的元素,我们将a[0]与最后一个元素进行交换,然后再将前9个数建堆。

将a[0]与a[8]交换,如下图:

重复上述操作,直到a[0]与a[0]交换的时候就停止,这时就已经排好序了。

时间复杂度:
第一次建堆的时间复杂度:O(N*lgN)。
每次调整的时间复杂度是O(lgN),总共有N次,即:O(N*lgN);
所以:
堆排序的时间复度:O(N*lgN)

2、升序排列。
  同理,升序排列要借助于最大堆。

完整代码:
[cpp] view plain copy
  1. #pragma once  
  2. #include<cassert>  
  3. template<typename T>  
  4. struct UpOder  
  5. {  
  6.     bool operator()(const T& l,const T& r)    //升序  
  7.     {  
  8.         return l < r;  
  9.     }  
  10. };  
  11.   
  12. template<typename T>            //降序  
  13. struct DownOder  
  14. {  
  15.     bool operator()(const T& l, const T& r)  
  16.     {  
  17.         return l>r;  
  18.     }  
  19. };  
  20.   
  21. //默认堆排序是升序,可通过仿函数传递参数设置为降序  
  22. template<typename T,class Compare=UpOder<T>>  
  23. class HeapSort  
  24. {  
  25. public:  
  26.     HeapSort()  
  27.     {}  
  28.     void Sort(T* a, int size)  
  29.     {  
  30.         //建堆  
  31.         assert(a);  
  32.         for (int i = (size - 2) / 2; i >= 0; --i)  
  33.         {  
  34.             AdjustDown(a, i, size);  
  35.         }  
  36.   
  37.         //堆排序  
  38.         while (size >1)     
  39.         {  
  40.             swap(a[0],a[size-1]);  
  41.             --size;  
  42.             AdjustDown(a,0,size);             
  43.         }  
  44.     }  
  45. protected:  
  46.     //下滑调整  
  47.     void AdjustDown(T* a,int root,int size)  
  48.     {  
  49.         assert(size>0);  
  50.         int parent = root;  
  51.         int child = parent * 2 + 1;  
  52.         while (child < size)  
  53.         {  
  54.             if ((child + 1) < size&&Compare()(a[child],a[child+1]))  
  55.                 child++;  
  56.             if (Compare()(a[parent], a[child]))  
  57.             {  
  58.                 swap(a[parent],a[child]);  
  59.                 parent = child;  
  60.                 child = parent * 2 + 1;  
  61.             }  
  62.             else  
  63.             {  
  64.                 break;  
  65.             }  
  66.         }  
  67.     }  
  68. };  
原创粉丝点击