详解归并排序 附代码 时间复杂度推导

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_31617121/article/details/79249546

归并排序有个merge()方法,是将两个排好序的数组合并成一个有序数组。时间复杂度能稳定在O(NlogN),时间复杂度证明如下图所示。不想快速排序,如果碰到有序的数组,快速排序会退化到O(N^2)
归并排序空间复杂度O(NlogN),证明如下
这里写图片描述

public class Solution {
    public static Integer[] tmp;

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

    public static void Mergesort(Integer[] a,int start, int end, Integer[] tmp){
        if (end == start){
            return;
        }
        int mid = (end-start)/2 + start;
        Mergesort(a, start, mid, tmp);
        Mergesort(a, mid+1, end, tmp);
        Merge(a, start, mid, end, tmp);
    }
    public static void Merge(Object[] a, int start, int mid, int end, Object[] tmp){
        int index = 0;
        int i = start, j = mid+1;
        while (i <= mid && j<= end){
            if (((Comparable)a[i]).compareTo(a[j]) <= 0){
                tmp[index++] = a[i];
                ++i;
            }
            else {
                tmp[index++] = a[j];
                ++j;
            }
        }
        while (i <= mid){
            tmp[index++] = a[i];
            i++;
        }
        while (j <= end){
            tmp[index++] = a[j];
            ++j;
        }
        for (int k = 0; k< index;++k){
            a[start+k] = tmp[k];
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页