heapsort.hxx

Go to the documentation of this file.
00001 
00002 
00003 #ifndef CH_TOOLS__HEAPSORT_HXX
00004 #define CH_TOOLS__HEAPSORT_HXX
00005 
00014 #include "mymath.hxx"
00015 
00016 namespace CH_Tools {
00017 
00036  
00043   template<class I,class V> void heapify(int i, int n, I& ind,const V& val);
00044 
00050   template<class I,class V> void build_heap(int n, I& ind, const V& val);
00051 
00057   template<class I,class V> void heapsort(int n, I& ind, const V& val);
00058 
00059 
00061 
00062 //--------------------------------------------------------------
00063 //                    heapsort -- implementation
00064 //--------------------------------------------------------------
00065 
00066 
00067 template<class I,class V> inline void heapify(int i,int n,I& ind,const V& val)
00068 {
00069  int k,j;
00070  k=i;
00071  while(2*k+1<n){
00072    using namespace CH_Matrix_Classes;
00073    if (2*k==n-2){
00074      if (val[ind[k]]<val[ind[2*k+1]])
00075        swap(ind[k],ind[2*k+1]);
00076      break;
00077    }
00078    if ((val[ind[k]]<val[ind[2*k+1]])||
00079        (val[ind[k]]<val[ind[2*k+2]])){
00080      if (val[ind[2*k+1]]>val[ind[2*k+2]]) j=2*k+1;
00081          else j=2*k+2;
00082      swap(ind[k],ind[j]);
00083      k=j;
00084    }
00085    else break;
00086  }
00087 }
00088 
00089 template<class I,class V> inline void build_heap(int n,I& ind,const V& val)
00090 {
00091  for(int i=n/2;--i>=0;) heapify(i,n,ind,val);
00092 }
00093 
00094 template<class I,class V> inline void heapsort(int n,I& ind,const V& val)
00095 {
00096  int i;
00097 
00098  //build heap
00099  build_heap(n,ind,val);
00100 
00101  //extract greatest and rebuild heap
00102  for(i=n;--i>=1;){
00103    using namespace CH_Matrix_Classes;
00104    swap(ind[i],ind[0]);
00105    heapify(0,i,ind,val);
00106  }
00107 }
00108 
00109 
00110 
00111 }
00112 
00113 #endif
00114 

Generated on Tue May 3 16:52:53 2011 for ConicBundle by  doxygen 1.5.6