码迷,mamicode.com
首页 > 其他好文 > 详细

2.1.17

时间:2018-05-30 17:32:07      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:win   read   show   one   make   IV   imp   宽度   array   

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);
     }
 }

 

2.1.17

标签:win   read   show   one   make   IV   imp   宽度   array   

原文地址:https://www.cnblogs.com/w-j-c/p/9111842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!