package com.test1;
public class MergeSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={1,3,4,9,6,2,5};
System.out.print("排序前:");
printArray(a);
int[] sorted=mergeSort(a, 0, a.length-1);
System.out.print("排序后:");
printArray(sorted);
}
public static int[] mergeSort(int[] a,int head,int tail) {
if (head==tail) {
int[] b={a[head]};
return b;
}
int mid=(head+tail)/2;
int[] toMerge1=new int[mid-head+1];
int[] toMerge2=new int[tail-mid];
toMerge1=mergeSort(a, head, mid);
toMerge2=mergeSort(a, mid+1, tail);
return merge(toMerge1,toMerge2);
}
public static int[] merge(int[] a1,int[] a2) {
int[] temp=new int[a1.length+a2.length];
int i=0,j=0,p=0;
while(i<a1.length&&j<a2.length){
if (a1[i]<=a2[j]) {
temp[p++]=a1[i++];
}else {
temp[p++]=a2[j++];
}
}
while (j<a2.length) {
temp[p++]=a2[j++];
}
while (i<a1.length) {
temp[p++]=a1[i++];
}
return temp;
}
public static void printArray(int[] a){
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
}