package sort;
public class MergeSort {
public void mergearray(int a[],int first,int mid,int last,int temp[]){//合并两个有序序列,合并后依然有序。
int i=first;
int j=mid;
int m=mid+1;
int n=last;
int k=0;
while(i<=j&&m<=n){
if(a[i]<a[m]){
temp[k++]=a[i++];
}else{
temp[k++]=a[m++];
}
}
while(i<=j){
temp[k++]=a[i++];
}
while(m<=n){
temp[k++]=a[m++];
}
for(int p=0;p<k;p++){
a[first+i]=temp[i];
}
}
public void mergesort(int a[], int first, int last, int temp[]){
if(first<last){
int mid=(first+last)/2;
mergesort(a, first, mid, temp);
mergesort(a,mid+1,last,temp);//先分治在合并
mergearray(a,first,mid,last,temp);//合并
}
}
}
public class MergeSort {
public void mergearray(int a[],int first,int mid,int last,int temp[]){//合并两个有序序列,合并后依然有序。
int i=first;
int j=mid;
int m=mid+1;
int n=last;
int k=0;
while(i<=j&&m<=n){
if(a[i]<a[m]){
temp[k++]=a[i++];
}else{
temp[k++]=a[m++];
}
}
while(i<=j){
temp[k++]=a[i++];
}
while(m<=n){
temp[k++]=a[m++];
}
for(int p=0;p<k;p++){
a[first+i]=temp[i];
}
}
public void mergesort(int a[], int first, int last, int temp[]){
if(first<last){
int mid=(first+last)/2;
mergesort(a, first, mid, temp);
mergesort(a,mid+1,last,temp);//先分治在合并
mergearray(a,first,mid,last,temp);//合并
}
}
}