Java之“归并排序”

归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。归并排序是一种稳定的排序方法。

思想:将两个已排好序的数组合并成一个有序的数组,先把待排序区间[s,t]以中点二分,接着把左边子区间排序,再把右边子区间排序,最后把左区间和右区间用一次归并操作合并成有序的区间[s,t]。

public class Main {
    public static void main(String[] args) {
        int[] a = new int[15];

        for (int i = 0; i < a.length; i++) {
            a[i] = (int) (Math.random() * 100);
        }

        for (int i : a) {
            System.out.print(i + " ");
        }

        System.out.println();
        int[] b = mestquick(a, 0, a.length - 1);
        for (int i : b) {
            System.out.print(i + " ");
        }

        System.out.println();

    }

    public static int[] mestquick(int[] c, int L, int R) {

        if (L == R) {
            return new int[]{c[L]};
        }
        int m = (L + R) / 2;
        int[] l = mestquick(c, L, m);//递归调用生成左有序组
        int[] r = mestquick(c, m + 1, R);//递归调用生成右 有序组
        int[] b = new int[l.length + r.length];//新有序数组

        int p = 0, i = 0, j = 0;
        while (i < l.length && j < r.length) {
            if (l[i] < r[j]) {
                b[p] = l[i];
                i++;
                p++;
            } else {
                b[p] = r[j];
                j++;
                p++;
            }
        }
        while (i < l.length) {
            b[p++] = l[i++];
        }
        while (j < r.length) {
            b[p++] = r[j++];
        }
        return b;
    }
}

附运行截图
在这里插入图片描述

发布了23 篇原创文章 · 获赞 0 · 访问量 806

猜你喜欢

转载自blog.csdn.net/qq_43581283/article/details/104341787