Java算法-归并排序

归并排序:分而治之,先自上而下递归拆分为左右两部分,并分别排序;再自下而上合并子数组的排序结果。

import java.util.Arrays;

/**
 * 归并排序
 **/
public class MergeSorter {
    public static void main(String[] args) {
        int[] data = {2, 3, 5, 4, 1, 2};
        data = mergeSort(data);
        // [1, 2, 2, 3, 4, 5]
        System.out.println(Arrays.toString(data));
    }

    private static int[] mergeSort(int[] data) {
        if (data.length <= 1) {
            return data;
        }
        int mid = data.length >> 1;
        // 拆分
        int[] leftData = Arrays.copyOfRange(data, 0, mid);
        int[] rightData = Arrays.copyOfRange(data, mid, data.length);
        // 合并
        return merge(mergeSort(leftData), mergeSort(rightData));
    }

    private static int[] merge(int[] leftData, int[] rightData) {
        int[] res = new int[leftData.length + rightData.length];
        int left = 0;
        int right = 0;
        int index = 0;
        // 按照从小到大顺序,合并左右两部分有序数组
        while (left < leftData.length && right < rightData.length) {
            if (leftData[left] <= rightData[right]) {
                res[index++] = leftData[left++];
            } else {
                res[index++] = rightData[right++];
            }
        }
        // 处理剩余元素
        while (left < leftData.length) {
            res[index++] = leftData[left++];
        }

        while (right < rightData.length) {
            res[index++] = rightData[right++];
        }
        return res;
    }
}

你可能感兴趣的:(算法,Java)