归并排序

来源:互联网 发布:马自达3 知乎 编辑:程序博客网 时间:2024/06/03 17:46

#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
#include<time.h>
using namespace std;

template<class T>
class CMP //抽象操作符类
{
 public:
  virtual bool operator()(const T&one,const T&other)=0; //纯虚函数,重载操作符()
};

template<class T>
class LessThan:public CMP<T> //小于操作符类
{
 public:
  bool operator()(const T&one,const T&other)
  {
   return one<other;
  }
};

template<class T>
class GreatThan:public CMP<T>
{
 public:
  bool operator()(const T&one,const T&other)
  {
   return one>other;
  }
};

template<class Iterator,class T> //待排序元素的类型
class Sort //抽象排序类
{
 protected:
  Iterator array; //指向待排序区间的开始指针
 public:
  virtual void operator()(const Iterator &beg,const Iterator &end,CMP<T> &cmp)=0;
};

template<class Iterator,class T>
class MergeSort:public Sort<Iterator,T>
{
 private:
  int low,high; //指向待排序区间开始和结束
  void Merge(int s,int t,int p,int q,CMP<T>&cmp); //将区间[s...t],[p...q]归并为有序区间
  void Sort_Function(int low,int high,CMP<T>&cmp); //将区间[low...high]归并排序
 public:
  void operator()(const Iterator &beg,const Iterator &end,CMP<T> &cmp)
  {
   low=0;
   high=end-beg-1;
   array=beg;
   Sort_Function(low,high,cmp);
  }
};

template<class Iterator,class T>
void MergeSort<Iterator,T>::Merge(int s,int t,int p,int q,CMP<T> &cmp)
{
 int len=q-s+1;
 T *tmp=new T[len];
 int i,j,k;
 i=s;
 j=p;
 k=0;
 while(i<=t && j<=q)
 {
  if(cmp(array[i],array[j])) tmp[k]=array[i++];
  else tmp[k]=array[j++];
  k++;
 }
 while(i<=t)
 {
  tmp[k++]=array[i++];
 }
 while(j<=q)
 {
  tmp[k++]=array[j++];
 }
 for(i=s,k=0;k<len;i++,k++)
 {
  array[i]=tmp[k];
 }
}

template<class Iterator,class T>
void MergeSort<Iterator,T>::Sort_Function(int low,int high,CMP<T> &cmp)
{
 if(low<high)
 {
  int mid=(low+high)/2;
  Sort_Function(low,mid,cmp);
  Sort_Function(mid+1,high,cmp);
  this->Merge(low,mid,mid+1,high,cmp);
 }
}
template<class Iterator,class T>
void Merge_Sort(const Iterator &beg,const Iterator &end,CMP<T>&cmp)
{
 MergeSort<Iterator,T> ms;
 ms(beg,end,cmp);
}

void main()
{
 vector<int>a;
 int x;
 srand((unsigned)time(0));
 const int n=80;
 for(int i=0;i<n;i++)
 {
  x=rand()%n;
  a.push_back(x);
 }
 //Merge_Sort<vector<int>::iterator,int>(a.begin(),a.end(),GreatThan<int>());
 Merge_Sort<vector<int>::iterator,int>(a.begin(),a.end(),LessThan<int>());
 copy(a.begin(),a.end(),ostream_iterator<int>(cout," "));
 cout<<endl;
}