思路:
1 设置中间值mid=(left+right)/2用来把原数组分成两个部分(left, mid)(mid+1, right)
2 不断将划分后的的数组分成两部分,直到不能再分(要求left
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner inp=new Scanner(System.in);
int n=inp.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=inp.nextInt();
s(a,0,n-1);
for(int i=0;i<n;i++)System.out.print(a[i]+" ");
}
public static void s(int a[],int left,int right){
if(left<right){
int mid=(left+right)/2;
s(a, left, mid);
s(a, mid+1, right);
int b[]=new int[a.length];
m(a,b,left,mid,right);
copy(a,b,left,right);
}
}
public static void m(int a[],int b[],int left,int mid,int right){
int l=left,ll=mid,r=mid+1,rr=right,j=left;
while(l<=ll&&r<=rr){
if(a[l]<=a[r])b[j++]=a[l++];
else b[j++]=a[r++];
}
if(l>ll)for(int i=r;i<=rr;i++)b[j++]=a[i];
else for(int i=l;i<=ll;i++)b[j++]=a[i];
}
public static void copy(int a[],int b[],int left,int right){
for(int i=left;i<=right;i++)a[i]=b[i];
}
}