归并排序算法Java实现

public class MergeSort {


    public static int[] MergeSort(int[] array) {
        if (array.length < 2)
            return array;

        int mid = array.length / 2;
        int[] left = Arrays.copyOfRange(array, 0, mid);
        int[] right = Arrays.copyOfRange(array, mid, array.length);
        return merge(MergeSort(left), MergeSort(right));
    }

    private static int[] merge(int[] left, int[] right) {
        int[] array = new int[left.length + right.length];

        for (int index = 0, i = 0, j = 0; index < array.length; index++) {
            if (i >= left.length) {
                array[index] = right[j++];
            } else if (j >= right.length) {
                array[index] = left[i++];
            } else if (left[i] < right[j]) {
                array[index] = left[i++];
            } else {
                array[index] = right[j++];
            }
        }
        return array;
    }
}

你可能感兴趣的:(归并排序算法Java实现)