package com.sort;


import java.util.Arrays;
public class MergeSort {
    public static void main(String[] args) {
        int[] a = new int[] {7, 8, 8, 6, 5, 59, 4, 3, 2, 1, 0};
        apartSort(a, 0, a.length-1);
        System.out.println(Arrays.toString(a));
    }

    /**
     * 分的过程
     * */
    private static void apartSort(int[] a, int left, int right) {
        int mid = (left + right) / 2;
        if (left < right) { //left=right时,表示只有一个元素,不需要再进行分了
            apartSort(a, left, mid);
            apartSort(a, mid + 1, right);
            mergsort(a, left, mid, right);
        }
    }

    private static void mergsort(int[] a, int left, int mid, int right) {
        int[] temp = new int[a.length];
        int point1 = left;
        int point2 = mid + 1;
        int loc = left;
        while (point1 <= mid && point2 <= right) {
            if (a[point1] < a[point2]) {
                temp[loc] = a[point1];
                loc++;
                point1++;
            } else {
                temp[loc] = a[point2];
                loc++;
                point2++;
            }
        }

        while (point1 <= mid) {
            temp[loc++] = a[point1++];
        }

        while (point2 <= right) {
            temp[loc++] = a[point2++];
        }
        for (int i = left; i <= right; i++) {
            a[i] = temp[i];
        }
    }
}