Java top-down merge sort implementation (int type)

If the algorithm can sort two subarrays, then it can sort the entire array by merging the two subarrays.
Time complexity: NlogN, space complexity: N

The situation before the auxiliary array is merged is shown in the figure:
final merge
Code:

public class MergeTD {

    public static void main(String[] args) {
        int[] a = { 2, 10, 7, 4, 8, 5, 9, 0, 1, 3, 6 };
        sort(a);
        System.out.println(Arrays.toString(a));
        a = new int[] {3,2,1,0};
        sort(a);
        System.out.println(Arrays.toString(a));
    }

    public static void sort(int[] a) {
        int[] aux = new int[a.length];
        sort(a, 0, a.length - 1,aux);
    }

    private static void sort(int[] a, int lo, int hi,int[] aux) {
        if (hi <= lo)
            return;
        int mid = lo + (hi - lo) / 2;
        sort(a, lo, mid,aux);//左边部分排序
        sort(a, mid + 1, hi,aux);//右边部分排序
        merge(a, lo, mid, hi,aux);//合并结果
    }

    public static void merge(int[] a, int lo, int mid, int hi, int[] aux) {
        int i = lo;//左指针
        int j = mid + 1;//右指针
        //复制数组
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k];
        }

        for (int k = lo; k <= hi; k++) {
            if (j > hi) {//右半边用尽
                a[k] = aux[i++];
            } else if (i > mid) {//左半边用尽
                a[k] = aux[j++];
            } else if (aux[i] < aux[j]) {//左半边元素小于右半边元素
                a[k] = aux[i++];//取左半边
            } else {//右半边元素小于左半边元素
                a[k] = aux[j++];//取右半边
            }
        }
    }
}

Improvement: Remove the code in the inner loop to judge whether a half edge is used up in the merge method. That is, copy the second half of a[] to the auxiliary array in descending order, so the result of sorting is unstable.
The situation before the auxiliary array is merged is shown in the figure:
write picture description here
Code:

public static void merge(int[] a, int lo, int mid, int hi, int[] aux) {
    int i = lo;// 左指针
    int j = hi;// 右指针
    for (int k = lo; k <= mid; k++) {
        aux[k] = a[k];
    }

    // 后半部分降序复制到辅助数组中
    for (int k = mid + 1; k <= hi; k++) {
        aux[hi - k + mid + 1] = a[k];
    }

    for (int k = lo; k <= hi; k++) {
        if (aux[i] < aux[j]) {
            a[k] = aux[i++];
        } else {
            a[k] = aux[j--];
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324511007&siteId=291194637