2.3.1

question:

Show, in the style of the trace given with partition(), how that method patitions the array E A S Y Q U E S T I O N.

answer:

import edu.princeton.cs.algs4.*;

public class Partition
{
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
   
    private static void exch(Comparable[] a, int x, int y)
    {
        Comparable t = a[x];
        a[x] = a[y];
        a[y] = t;
    }
    
    public static int partition(Comparable[] a, int lo, int hi)
    {
        int i = lo, j = hi + 1;
        Comparable v = a[lo];
        show(a,i,j);
        while(true)
        {
            while(less(a[++i],v))
            {
                if(i == hi)
                    break;
            }
            while(less(v,a[--j]))
            {
                if(j == lo)
                    break;
            }
            if(i >= j)
                break;
            show(a,i,j);
            exch(a, i, j);
            show(a,i,j);
        }
        show(a,i,j);
        exch(a,lo,j);
        show(a,i,j);
        return j;
    }
    
    public static void show(Comparable[] a, int i, int j)
    {
        StdOut.printf("%d %d ", i, j);
        for(int t = 0; t < a.length; t++)
            StdOut.print(a[t] + " ");
        StdOut.println();
    }
    
    public static void main(String[] args)
    {
        //输入E A S Y Q U E S T I O N
        String[] a = In.readStrings();
        int c = partition(a, 0, a.length-1);
        StdOut.println(c);
    }
}

猜你喜欢

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