2.1.18

question:

Visual trace. Modify your solution to the previous exercise to make Insertion and Selection produce visual traces such as those depicted in this section. Hint: Judicious use of setYscale() makes this problem easy. Extra credit: Add the code necessary to produce red and gray color accents such as those in our figures.

answer:

//不明白这题与上一道有什么区别(可视轨迹和动画有区别吗),我就加了个当前最小红色和已排序灰色,没用setYscale()

//然后只写了个Selection的,

import edu.princeton.cs.algs4.*; 

public class Selection
 {
     public static void sort(double[] a)
     {
         int N = a.length;
         int min;
         for(int i = 0; i < N; i++)
         {
             min = i;
             for(int j = i+1; j < N; j++)
             {
                 if(less(a[j], a[min]))
                     min = j;
             }
             show(a,min,i);
             exch(a,i,min);
         }
     }
     
     private static boolean less(double v, double w)
     {
         return v - w < 0;
     }
     
     private static void exch(double[] a, int i , int j)
     {
         double t = a[i];
         a[i] = a[j];
         a[j] = t;
     }
     
     private static void show(double[] a, int current, int sorted)
     {
         int N = a.length;
         try//延时1000毫秒
         {   
             Thread.currentThread().sleep(1000);
         }   
         catch(Exception e){}  
         StdDraw.clear(StdDraw.WHITE);
         for(int t = 0; t < N; t++)
             {
                 double x = 1.0 * t/N + 0.5/N;//0.5/N就是rw,即矩形半个宽度,这样第一个矩形就不会只有一半了
                 double y = a[t]/2.0;
                 double rw = 0.5/N;
                 double rh = a[t]/2.0;
                 if(t == current)
                 {
                     StdDraw.setPenColor(StdDraw.RED);
                     StdDraw.filledRectangle(x, y, rw, rh);
                     StdDraw.setPenColor(StdDraw.BLACK);
                 }
                 else if(t < sorted)
                 {
                      StdDraw.setPenColor(StdDraw.GRAY);
                      StdDraw.filledRectangle(x, y, rw, rh);
                      StdDraw.setPenColor(StdDraw.BLACK);
                 }
                 else
                     StdDraw.filledRectangle(x, y, rw, rh);
             }
     }
     
     public static boolean isSorted(double[] a)
     {
         for(int i = 1; i < a.length; i++)
         {
             if(less(a[i],a[i-1]))
                 return false;
         }
         return true;
     }
     
     public static void main(String[] args)
     {
         int N = 20;
         double a[] = new double[N];
         for(int i = 0; i < N; i++)
             a[i] = StdRandom.random();
         sort(a);
         assert isSorted(a);
     }
 }

猜你喜欢

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