归并排序
来源:互联网 发布:马自达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;
}
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- android 图片旋转
- CSS 兼容大全
- hdu 3270 The Diophantine Equation
- 第十二周实验指导--任务四--类的组合与继承
- 防CSS代码挂马
- 归并排序
- 缓存类
- tiny 210 编译出错解决/init: line 103: can't open /r/dev/console: no such file
- 华为南研2011年“Openday”
- android GPS定位系统
- ssh配置文件
- VB.NET 连接 SAP RFC(SAP Connection 3.0)
- 第十二周实验指导--任务三--设计一个在下面一段类的定义中,自行车类的虚基类为车辆类,机动车类的虚基类也为车辆类,摩托车类的基类为自行车类和机动车类,类之间均为公有继承
- mips中的read、write、ioremap、out、in函数