#include<iostream> using namespace std; const int N=10; template <class Type> class ArraySort { public: ArraySort(Type *,int ); void Preprint(); void Sort(); void Merge(int ,int ,int ); void MergeSort(int ,int ); void Print(); ~ArraySort(); private: int flag; // 0为升序,1为降序 Type *array; Type *result; int len; }; template <class Type> void ArraySort<Type>::Preprint() { for(int i=0;i<len;i++) cout<<array[i]<<" "; cout<<endl; } template <class Type> void ArraySort<Type>::Sort() { MergeSort(0,N); } template <class Type> ArraySort<Type>::ArraySort(Type *a,int b ) { array=new Type[b]; result=new Type[b]; len=b; if(array==NULL || result==NULL) cerr<<"can't allocate more memory"; for(int i=0;i<len;i++) array[i]=a[i]; int m; T:; cout<<"Input the number 0 or 1:"<<endl; cout<<"0 min to max"<<endl; cout<<"1 max to min"<<endl; cin>>m; if(m>=0 && m<=1) flag=m; else { cout<<"You input a illege number."; goto T; } } template <class Type> void ArraySort<Type>::MergeSort(int left,int right) { int div; if(left<right-1) { div=(left+right)/2; MergeSort(left,div); MergeSort(div,right); Merge(left,div,right); } } template <class Type> void ArraySort<Type>::Merge(int begin,int div,int end) { int i=begin; int j=div; int k=begin; if(flag==0) { while(i<div && j<end) { if(array[i]<=array[j]) result[k++]=array[i++]; else result[k++]=array[j++]; } } else { while(i<div && j<end) { if(array[i]<=array[j]) result[k++]=array[j++]; else result[k++]=array[i++]; } } while(i<div) result[k++]=array[i++]; while(j<end) result[k++]=array[j++]; memcpy(array+begin,result+begin,(end-begin)*sizeof(Type)); } template <class Type> void ArraySort<Type>::Print() { if(flag==0) cout<<"按升序排序后的数组:"<<endl; else cout<<"按降序排序后的数组:"<<endl; for(int i=0;i<len;i++) cout<<result[i]<<" "; cout<<endl; } template <class Type> ArraySort<Type>::~ArraySort() { delete []array; delete []result; } int main() { int test[N]={4,8,3,10,12,20,100,10,203,18}; ArraySort<int> temp(test,N); cout<<"排序前数组为:"<<endl; temp.Preprint(); temp.Sort(); temp.Print(); return 0; }