2.2.1

question:

Give atrace, in the style of the trace given at the beginning of this section, showing how the keys 

import edu.princeton.cs.algs4.*;

public class Merge
{
    public static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    public static void merge(Comparable[] a, int lo, int mid, int hi)
    {
        int i = lo, j = mid+1;
        Comparable[] aux = new Comparable[a.length];
        for(int k = 0; k < a.length; k++)
            aux[k] = a[k];
        
        for(int t = 0; t < a.length; t++)
        {
            if(i >= mid + 1)
                a[t] = aux[j++];
            else if(j >= a.length)
                a[t] = aux[i++];
            else if(less(aux[i],aux[j]))
                a[t] = aux[i++];
            else 
                a[t] = aux[j++];
           
            StdOut.print(t + " ");
            show(a,t);
        }
    }
    
    public static void show(Comparable[] a, int size)
    {
        for(int i = 0; i <= size; i++)
        {
            StdOut.print(a[i] + " ");
        }
        StdOut.println();
    }
    
    public static void main(String[] args)
    {
        //输入A E Q S U Y E I N O S T
        String[] a = In.readStrings();
        int lo = 0;
        int hi = a.length - 1;
        int mid = lo + (hi - lo)/2;
        merge(a,lo,mid,hi);
        show(a,hi);
    }
}

are merged with the abstract      in-place merge() method.

answer:

猜你喜欢

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