• Algs4-2.1.17动画-插入排序


    2.1.17动画。修改插入排序和选择排序的代码,使之将数组内容绘制成正文中所示的棒状图。在每一轮排序后重绘图片来产生动画效果,并以一张“有序”的图片作为结束,即所有圆棒均已按照高度有序排列。提示:使用类似于正文中的用例来随机生成Double值,在排序代码的适当位置调用show()方法,并在show()方法中清理画布并绘制棒状图。

    public class Insertion
    {
        public static void sort(Comparable[] a)
        {
            int N=a.length;
            for (int i=0;i<N;i++)
            {
                for(int j=i;j>0 && less(a[j],a[j-1]);j--)
                    exch(a,j,j-1);
                 showAnimation(a);
            }
        }
       
        private static boolean less(Comparable v,Comparable w)
        { return v.compareTo(w)<0;}
       
        private static void exch(Comparable[] a,int i,int j)
        {
            Comparable t=a[i];
            a[i]=a[j];
            a[j]=t;
        }
       
        private static void show(Comparable[] a)
        {
            for (int i=0;i<a.length;i++)
                StdOut.print(a[i]+" ");
            StdOut.println();
        }
       
        private static void showAnimation(Comparable[] a)
        {
           StdDraw.setXscale(0.0,a.length);
           StdDraw.setYscale(0.0,a.length);
           StdDraw.setPenRadius(0.005);
           StdDraw.pause(100);
           StdDraw.clear(StdDraw.GRAY);
           StdDraw.setPenColor(StdDraw.BLACK);
            for(int i=0;i<a.length;i++)
            {
                StdDraw.line(i*1.0,0.0,i*1.0,(Double)a[i]*1.0);
            }
        }
       
        public static boolean isSorted(Comparable[] a)
        {
            for (int i=0;i<a.length;i++)
                if(less(a[i],a[i-1])) return false;
            return true;
        }
       
         public static void main(String[] args)
        {
            int N=Integer.parseInt(args[0]);
            Double[] a=new Double[N];
            for(int i=0;i<N;i++)
                a[i]=StdRandom.uniform(0.0,N*1.0);
            //
            StdDraw.pause(5000);
            sort(a);
        }
    }

  • 相关阅读:
    ASP.NET Core结合Nacos来完成配置管理和服务发现
    一次业务网关用ASP.NET Core 2.1重构的小结
    给HttpClient添加请求头(HttpClientFactory)
    使用Redis实现最近N条数据的决策
    记一次Python与C#的AES加密对接
    按次计费接口的简单实现思路
    .NET Core 3 WPF MVVM框架 Prism系列文章索引
    异步函数async await在wpf都做了什么?
    .NET Core 3 WPF MVVM框架 Prism系列之对话框服务
    .NET Core 3 WPF MVVM框架 Prism系列之导航系统
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9860033.html
Copyright © 2020-2023  润新知