64,654
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
int x[8]={0,-1,1,18,5,3,9,9};
template <class T>
void PrintfNum(T a[], int n);
//Merge Sorting
template <class T>
void merge(T a[],T tmp[],int low,int middle,int high)
{
int x=0;
for(x=low;x<=high;x++) tmp[x]=a[x]; //copy to a tmp array
int PtLeft=low; //[low -- middle]
int PtRight=middle+1; //[middle+1 -- high]
int Current=low;
while( PtLeft<=middle && PtRight<=high )
{ if(tmp[PtLeft]<=tmp[PtRight])
{a[Current]=tmp[PtLeft];
PtLeft++;
}
else{
a[Current]=tmp[PtRight];
PtRight++;
}
Current++;
}
int remaining=middle-PtLeft;
int ccc=0;
for(int i=0;i<=remaining;i++){
a[Current+i]=tmp[PtLeft+i];
}
}
template <class T>
void mergesort1(T a[],T tmp[],int low,int high){
if(low<high){
int middle=(low+high)/2;
//cout<<"enter-Merge1-Left:"<<low<<','<<middle<<','<<high<<endl;
mergesort1<T>(a,tmp,low,middle);
//cout<<"enter-Merge1-Right:"<<low<<','<<middle<<','<<high<<endl;
mergesort1<T>(a,tmp,middle+1,high);
merge<T>(a,tmp,low,middle,high);
}
}
template <class T>
void mergesort(T a[],int length){
int *tmp=new int(8);
mergesort1<T>(a,tmp,0,length-1);
delete [] tmp;
}
int main(){
mergesort<int>(x,8);
PrintfNum<int>(x,8);
system("pause");
return 0;
}
template <class T>
void PrintfNum(T a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << ",";
}
cout << endl;
}