• Algs4-2.1.17动画-选择排序


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

    public class Selection
    {
        public static void sort(Comparable[] a)
        {
            int N=a.length;
            for (int i=0;i<N;i++)
            {
                int min=i;
                for (int j=i+1;j<N;j++)
                    if (less(a[j],a[min])) min=j;
                exch(a,i,min);
                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);
        }
    }

    转载于:https://www.cnblogs.com/longjin2018/p/9860034.html

  • 相关阅读:
    Jmeter 常用函数(20)- 详解 __counter
    Jmeter 常用函数(19)- 详解 __BeanShell
    Python 简明教程 --- 26,Python 多进程编程
    Python 简明教程 --- 25,Python 目录操作
    Python 简明教程 --- 24,Python 文件读写
    Zookeeper分布式过程协同技术
    设计模式之命令模式案例详解
    设计模式之模板方法模式
    设计模式之代理模式案例详解
    设计模式之享元模式
  • 原文地址:https://www.cnblogs.com/twodog/p/12135740.html
Copyright © 2020-2023  润新知