Solution.java 1.3 KB
Newer Older
漫长的~以后's avatar
漫长的~以后 已提交
1 2 3 4 5 6 7
class Solution {
    public static void mergeSort(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int[] helper = new int[nums.length];
        mergeSort(nums, helper, 0, nums.length - 1);
漫长的~以后's avatar
漫长的~以后 已提交
8 9
        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
漫长的~以后's avatar
漫长的~以后 已提交
10
        }
漫长的~以后's avatar
漫长的~以后 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    }

    private static void mergeSort(int[] nums, int[] helper, int low, int high) {
        if (low < high) {
            int middle = low + (high - low) / 2;
            mergeSort(nums, helper, low, middle);
            mergeSort(nums, helper, middle + 1, high);
            merge(nums, helper, low, middle, high);
        }
    }

    private static void merge(int[] nums, int[] helper, int low, int middle, int high) {
        for (int i = low; i <= high; i++) {
            helper[i] = nums[i];
        }

        int left = low;
        int right = middle + 1;
        int curr = low;
        while (left <= middle && right <= high) {
            if (helper[left] <= helper[right]) {
                nums[curr++] = helper[left++];
            } else {
                nums[curr++] = helper[right++];
            }
        }

        int remain = middle - left;
        for (int i = 0; i <= remain; i++) {
            nums[curr + i] = helper[left + i];
        }
    }
}