伪代码
MERGE(A,p,q,r) n1=q-p+1; n2=r-q; create new arrays L[n1+1] and R[n2+1] for i=0 to n1-1 L[i]=A[p+i] for j=0 to n2-1 R[j]=A[q+1+j] L[n1]=1000//假设1000是无穷大 R[n2]=1000 i=j=0 for k=p to r if(L[i]<=R[j]) A[k]=L[i] i=i+1 else A[k]=R[j] j=j+1 MERGE_SORT(A,p,r) if p<r q=floor((p+r)/2) MERGE_SORT(A,p,q) MERGE_SORT(A,q+1,r) MERGE(A,p,q,r)
c实现
void main(){
int A[]={3,8,1,4,5,0,2,5};
int i;
int len=sizeof(A)/sizeof(A[0]);
merge_sort(A,0,7);
for(i=0;i<len;i++){
printf("%d ",A[i]);
}
}
void merge(int A[],int p,int q,int r){
int n1,n2,i,j,k;
n1=q-p+1;
n2=r-q;
int L[n1+1];
int R[n2+1];
for(i=0;i<n1;i++){
L[i]=A[p+i];
}
for(j=0;j<n2;j++){
R[j]=A[q+j+1];
}
L[n1]=1000;//假设100是无穷大的数
R[n2]=1000;
i=0;
j=0;
for(k=p;k<=r;k++){
if(L[i]<=R[j]){
A[k]=L[i];
i=i+1;
}else{
A[k]=R[j];
j=j+1;
}
}
}
void merge_sort(int A[],int p,int r){
int q;
if(p<r){
q=floor((p+r)/2);
merge_sort(A,p,q);
merge_sort(A,q+1,r);
merge(A,p,q,r);
}
}
java实现
public class Main {
public static void main(String[] args) {
int [] arr={3,8,1,4,5,0,2,5};
merge_sort(arr,0,7);
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
public static void merge(int [] arr,int p,int q,int r){
int len1=q-p+1;
int len2=r-q;
int [] arrLeft=new int[len1+1];
int [] arrRight=new int[len2+1];
for(int i=0;i<len1;i++){
arrLeft[i]=arr[p+i];
}
for(int j=0;j<len2;j++){
arrRight[j]=arr[q+1+j];
}
arrLeft[len1]=1000;
arrRight[len2]=1000;
int i=0;
int j=0;
for(int k=p;k<=r;k++){
if(arrLeft[i]<=arrRight[j]){
arr[k]=arrLeft[i];
i++;
}else{
arr[k]=arrRight[j];
j++;
}
}
}
public static void merge_sort(int [] arr,int p,int r){
if(p<r){
int q=(int)Math.floor((p+r)/2);
merge_sort(arr,p,q);
merge_sort(arr,q+1,r);
merge(arr,p,q,r);
}
}
}