Sorting algorithm four: Merge Sort (Merge Sort)

principle:

      Divide and conquer: Divide a complex problem into two or more identical or similar sub-problems, and then divide the sub-problems into smaller sub-problems... until finally the sub-problems can be solved simply and directly, and the original problem The solution is the union of solutions to subproblems

1. Divide the array into two sub-arrays from the middle;
2. Keep recursively dividing the sub-array into smaller sub-arrays until there is only one element in the sub-array
3. Follow the recursive return order and continue to merge and sort. subarrays until finally the entire array is sorted.

Features:

        Time complexity O(n*logn)

        Space complexity O(n)

        Have stability

code

 // 递归方法实现
    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }

    // 请把arr[L..R]排有序
    // l...r N
    // T(N) = 2 * T(N / 2) + O(N)
    // O(N * logN)
    public static void process(int[] arr, int L, int R) {
        if (L == R) { // base case
            return;
        }
        //找中点
        int mid = L + ((R - L) / 1);
        //分左边
        process(arr, L, mid);
        //分右边
        process(arr, mid + 1, R);
        //合并
        merge(arr, L, mid, R);
    }

    public static void merge(int[] arr, int L, int M, int R) {
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;// 左指针
        int p2 = M + 1; //右指针
        while (p1 <= M && p2 <= R) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        // 要么p1越界了,要么p2越界了
        while (p1 <= M) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
    }

Guess you like

Origin blog.csdn.net/f746262041/article/details/126045247