堆排序

#ifndef HEAP_SORT_H
#define HEAP_SORT_H

#include<assert.h>
template<class T,int n>
inline void swap(T* s,int i,int j)
{
	assert((i<n)&&(j<n));
	T temp=s[i];
	s[i]=s[j];
	s[j]=temp;
}

template<class T,int n>
inline int leftChild(int i){
    return 2*i+1;
}

template<class T,int n>
inline int rightChild(int i){
	return 2*i+2;
}

template<class T,int n> 
void build_heap(T* s)
{
	int i=(n-1)/2;
	for(;i>=0;i--)
		keep_heap<T,n>(s,i,n);
}
template<class T,int n>
void keep_heap(T* s,int root,int heap_size)
{
   int min;
   if(s[root]>s[leftChild<T,n>(root)]&&leftChild<T,n>(root)<heap_size-1)	
	   min=leftChild<T,n>(root);
   else
	   min=root;

   if(s[min]>s[rightChild<T,n>(root)]&&rightChild<T,n>(root)<heap_size-1)
	  min=rightChild<T,n>(root);
   if(min!=root)
	 {
		swap<T,n>(s,min,root);
		keep_heap<T,n>(s,min,heap_size);
	 }
}
template<class T,int n>
void heap_sort(T *s)
{
   build_heap<T,n>(s); 
   int i=n-1;
   while(i)
   {
     swap<T,n>(s,0,i);
	 keep_heap<T,n>(s,0,i+1);
	 i--;	 
   }

}
#endif
posted @ 2011-07-19 19:57  樱色布  阅读(165)  评论(0编辑  收藏  举报