Java 杂谈程序猿阵线联盟-汇总各类技术干货高薪算法+计算机职称考试

常用排序算法专题—归并排序

2019-03-21  本文已影响295人  9f5e612a0d44

归并排序

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

  在计算机科学中,分治法是一种很重要的算法。字面上的解释是“分而治之”,就是把一个复杂的问题分成两个或更多的相同或相似的子问题,再把子问题分成更小的子问题,直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合并。
  我们可以看到上图中,待排序数组为{4,8,2,7,1,6,3,5},我们先将它们分解成{4,8,2,7}{1,6,3,5}两部分,将这两部分继续分解为{4,8}、{2,7}和{1,6}、{3、5};以此类推,分解的过程完成。接着我们将4,8,2,7,1,6,3,5两两排序合并,变成{4,8}、{2,7}、{1,6}、{3、5},紧接着继续将以上四部分两两排序合并,变成{2,4,7,8}{1,3,5,6},最后再将这两部分排序合并,排序完成。

注:我们发现 j 指针已经指向结尾,那么把前一个数组的剩余数据按顺序移到temp数组。


  此时两个已经有序的子序列合并成了一个有序序列。

JAVA 代码

package DataStructure;

public class MergeSort {

    public static void sort(int[] arr, int low, int high, int[] temp) {
        if (low < high) {
            int mid = (low + high) / 2;
            sort(arr, low, mid, temp);
            sort(arr, mid + 1, high, temp);
            merge(arr, low, mid, high, temp); // 对两个子数组进行合并操作
        }
    }

    private static void merge(int[] arr, int low, int mid, int high, int[] temp) {
        int tempPoint = 0; // temp数组指针
        int i = low; // i指针
        int j = mid + 1; // j指针

        while (i <= mid && j <= high)
            if (arr[i] <= arr[j])
                temp[tempPoint++] = arr[i++];
            else
                temp[tempPoint++] = arr[j++];

        while (i <= mid)
            temp[tempPoint++] = arr[i++]; // 左边剩余的填充至temp数组中
        while (j <= high)
            temp[tempPoint++] = arr[j++]; // 右边剩余的填充至temp数组中

    
        int t = 0;
        while (low <= high)     // 返回至原数组
            arr[low++] = temp[t++];

    }

    public static void main(String[] args) {
        int[] arr = { 4, 8, 2, 7, 1, 6, 3, 5 };
        int[] temp = new int[arr.length];
        sort(arr, 0, arr.length - 1, temp);
        for (int n : arr)
            System.out.print(n + " ");
    }
}

  归并排序是稳定排序,它也是一种十分高效的排序,上图中可看出,每次合并操作的平均时间复杂度为O(n),而完全二叉树的深度为O(logn)。总平均时间复杂度为O(nlogn)。而且,归并排序的最好、最坏、平均时间复杂度均为O(nlogn)。

上一篇 下一篇

猜你喜欢

热点阅读