package com.thinker.suanfa.sort;

/**
 * @author lzh
 * 并归排序
 **/
public class MergeSort {

    /**
     *
     * @param arr
     */
    private static void mergeSort(int[] arr) {
        int[] tmp = new int[arr.length];
        internalMergeSort(arr, tmp, 0, arr.length - 1);
    }

    /**
     *
     * @param arr
     * @param tmp
     * @param left
     * @param right
     */
    private static void internalMergeSort(int[] arr, int[] tmp, int left, int right) {
        if (left < right) {
            int middle = (left + right) / 2;
            internalMergeSort(arr, tmp, left, middle);
            internalMergeSort(arr, tmp, middle + 1, right);
            mergeArray(arr, tmp, left, middle, right);
        }
    }

    /**
     *
     * @param arr
     * @param tmp
     * @param left
     * @param middle
     * @param right
     */
    private static void mergeArray(int[] arr, int[] tmp, int left, int middle, int right) {
        int i = left, j = middle + 1, k = 0;
        while (i <= middle && j <= right) {
            if (arr[i] <= arr[j]) {
                tmp[k++] = arr[i++];
            } else {
                tmp[k++] = arr[j++];
            }
        }
        while (i <= middle) tmp[k++] = arr[i++];
        while (j <= right) tmp[k++] = arr[j++];
        for (i = 0; i < k; i++)
            arr[left + i] = tmp[i];
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4, 2, 6, 8, 9, 3, 1, 5};
        long begin = System.nanoTime();
        mergeSort(arr);
        long end = System.nanoTime();
        for (int a : arr) {
            System.out.print(a + "\t");
        }
        System.out.println("\nrun time:" + (double) (end - begin) / 1000 + " ms");
    }
}
