1. package com.sort.s05mergesort;
    2. import java.util.Arrays;
    3. /**
    4. * @Author black_zhou
    5. */
    6. public class MergeSort {
    7. public int[] mergeSort(int[] arrays){
    8. if(null == arrays || arrays.length < 2){
    9. return arrays;
    10. }
    11. int mid = arrays.length/2;
    12. int[] left = Arrays.copyOfRange(arrays,0,mid);
    13. int[] right = Arrays.copyOfRange(arrays,mid,arrays.length);
    14. return merge(left,right);
    15. }
    16. private int[] merge(int[] left,int[] right){
    17. // 如果拆分后的数组只有一个元素后,最后调用mergeSort(),则会将该单个元素的数组返回,这里就是递归的终点
    18. int[] leftsort = mergeSort(left);
    19. int[] rightsort = mergeSort(right);
    20. // 递归的终点结束后,然后依次又往上层返回结果
    21. // 这里开始就将排好序的两个子数组合并为一个大的数组
    22. int length = leftsort.length + rightsort.length;
    23. int[] sortarray = new int[length];
    24. int l=0,r=0,i=0;
    25. while(l<leftsort.length && r<rightsort.length){
    26. if(leftsort[l]<rightsort[r]){
    27. sortarray[i] = leftsort[l];
    28. l++;
    29. }else{
    30. sortarray[i] = rightsort[r];
    31. r++;
    32. }
    33. i++;
    34. }
    35. while(l<leftsort.length){
    36. sortarray[i] = leftsort[l];
    37. l++;
    38. i++;
    39. }
    40. while(r<rightsort.length){
    41. sortarray[i] = rightsort[r];
    42. r++;
    43. i++;
    44. }
    45. return sortarray;
    46. }
    47. public void println(int [] a) {
    48. for(int x:a) {
    49. System.out.print(" "+x);
    50. }
    51. System.out.println("");
    52. }
    53. public static void main(String[] args) {
    54. int[] nums = {5, 3, 4, 6, 7, 1, 2, 8, 4, 10, 100, 50, 30, 22, 34, 55, 43, 12, 31};
    55. MergeSort sort = new MergeSort();
    56. sort.println(sort.mergeSort(nums));
    57. }
    58. }