2.2.7

question:

Show that the number of compares used by mergesort is monotonically increasing(C(N+1) > C(N) for all N > 0).

answer:

//比较仅仅指less()?

import edu.princeton.cs.algs4.*;

public class Merge
{
    private static Comparable[] aux;
    public static int count = 0;
    
    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)
    {
        count++;
        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);//排右侧
        merge(a,lo,mid,hi);//归并
    }
    
    public static void main(String[] args)
    {
        int N = 1;
        while(N <= 512)
        {
           Double[] a = new Double[N];
           for(int t = 0; t < N; t++)
               a[t] = StdRandom.uniform();
           sort(a);
           StdOut.println(count);
           count = 0;
           N++;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9118931.html
今日推荐