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

归并排序有个merge()方法,是将两个排好序的数组合并成一个有序数组。时间复杂度能稳定在O(NlogN),时间复杂度证明如下图所示。不想快速排序,如果碰到有序的数组,快速排序会退化到O(N^2)
归并排序空间复杂度O(NlogN),证明如下
详解归并排序 附代码 时间复杂度推导_第1张图片

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];
        }
    }
}

你可能感兴趣的:(数据结构与算法)