class MergeSort {
public:
;
void merge_(int a[],int first,int mid,int last,int b[]){
int i=first,j=mid+1;
int k=0;
while(i<=mid && j<=last){
if(a[i]<a[j]){
b[k++]=a[i];
i++;
}
else{
b[k++]=a[j];
j++;
}
}
while(i<=mid){
b[k++]=a[i++];
}
while(j<=last){
b[k++]=a[j++];
}
for(int i=0;i<k;i++){
a[first+i]=b[i];
}
}
void work(int a[],int first,int last,int b[]){
if(first<last){
int mid=first+(last-first)/2;
work(a,first,mid,b);
work(a,mid+1,last,b);
merge_(a,first,mid,last,b);
}
}
int* mergeSort(int* A, int n) {
// write code here
int *p=new int[n];
if(p==NULL){
return p;
}
work(A,0,n-1,p);
return A;
}
};
归并排序
最新推荐文章于 2023-09-03 20:36:33 发布