package com.sort.s05mergesort;
import java.util.Arrays;
/**
* @Author black_zhou
*/
public class MergeSort {
public int[] mergeSort(int[] arrays){
if(null == arrays || arrays.length < 2){
return arrays;
}
int mid = arrays.length/2;
int[] left = Arrays.copyOfRange(arrays,0,mid);
int[] right = Arrays.copyOfRange(arrays,mid,arrays.length);
return merge(left,right);
}
private int[] merge(int[] left,int[] right){
// 如果拆分后的数组只有一个元素后,最后调用mergeSort(),则会将该单个元素的数组返回,这里就是递归的终点
int[] leftsort = mergeSort(left);
int[] rightsort = mergeSort(right);
// 递归的终点结束后,然后依次又往上层返回结果
// 这里开始就将排好序的两个子数组合并为一个大的数组
int length = leftsort.length + rightsort.length;
int[] sortarray = new int[length];
int l=0,r=0,i=0;
while(l<leftsort.length && r<rightsort.length){
if(leftsort[l]<rightsort[r]){
sortarray[i] = leftsort[l];
l++;
}else{
sortarray[i] = rightsort[r];
r++;
}
i++;
}
while(l<leftsort.length){
sortarray[i] = leftsort[l];
l++;
i++;
}
while(r<rightsort.length){
sortarray[i] = rightsort[r];
r++;
i++;
}
return sortarray;
}
public void println(int [] a) {
for(int x:a) {
System.out.print(" "+x);
}
System.out.println("");
}
public static void main(String[] args) {
int[] nums = {5, 3, 4, 6, 7, 1, 2, 8, 4, 10, 100, 50, 30, 22, 34, 55, 43, 12, 31};
MergeSort sort = new MergeSort();
sort.println(sort.mergeSort(nums));
}
}