2.2.8

question:

Suppose that ALGORITHM 2.4 is modified to skip the call on merge() whenever a[mid] <= a[mid+1]. Prove that the number of compares used to mergesort a sorted array is linear.

answer:

//官网答案

Solution. Since the array is already sorted, there will be no calls to merge(). When N is a power of 2, the number of compares will satisfy the recurrence T(N) = 2 T(N/2) + 1, with T(1) = 0.

//我的代码

import edu.princeton.cs.algs4.*;

public class Merge
{
    private static Comparable[] aux;
    
    public static void sort(Comparable[] a)
    {
        aux = new Comparable[a.length];
        sort(a, 0, a.length-1);
    }
    
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    private static void show(Comparable[] a)
    {
        for(int i = 0; i < a.length; i++)
            StdOut.print(a[i] + " ");
        StdOut.println();
    }
    
    public static boolean isSorted(Comparable[] a)
    {
        for(int i = 1; i < a.length; i++)
            if(less(a[i], a[i-1])) return false;
        return true;
    }
    
    public static void merge(Comparable[] a, int lo, int mid, int hi)
{
    int i = lo, j = mid + 1;
    
    for(int k = lo; k <= hi; k++)//复制
        aux[k] = a[k];
    
    for(int k = lo; k <= hi; k++)//把a[]填满就退出循环
    {
        if(i > mid)//左侧已用完,则只能从右侧拿
            a[k] = aux[j++];
        else if(j > hi)//右侧已用完,则只能从左侧拿
            a[k] = aux[i++];
        else if(less(aux[i], aux[j]))//当前左侧比右侧小,从右侧拿
            a[k] = aux[i++];
        else//反之当前右侧比左侧小,从左侧拿
            a[k] = aux[j++];
    }
}
    
    private static void sort(Comparable[] a, int lo, int hi)
    {
        if(hi <= lo)
            return;
        int mid = lo + (hi - lo) / 2;//不用(a+b)/2是因为a+b可能超过int的上界,防止溢出
        sort(a,lo,mid);//排左侧
        sort(a,mid+1,hi);//排右侧
        if(!(a[mid].compareTo(a[mid+1])<0))//主要修改了这里
            merge(a,lo,mid,hi);//归并
    }
    
    public static void main(String[] args)
    {
        String[] a = In.readStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9118993.html