2.1.17

question:

Animation. Add code to Insertion and Selection to make them draw the array contents as vertical bars likes the visual traces in this section, redrawing the bars after each pass, to produce an animated effect, ending in a "sorted" picture where the bars appear in order of their height. Hint: Use a client like the one in the text that generates random Double valies, insert calls to show() as appropriate in the sort code, and inplement a show() method that clears the canvas and draws the bars.

answer:

//这是Insertion的,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;
             }
             exch(a,i,min);
             show(a);
         }
     }
     
     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 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;
                 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/9111842.html