zoukankan      html  css  js  c++  java
  • Algs4-2.1.18可视轨迹-插入排序

     2.1.18可视轨迹。修改你为上一题给出的解答,为插入排序和选择排序生成和正文中类似的可视轨迹。提示:使用setYscale()函数是一个明智的选择。附加题:添加必要的代码,与正文中的图片一样用红色和灰色强调不同角色的元素。
    图片 
    /******************************************************************************
     *  Compilation:  javac InsertionBars.java
     *  Execution:    java InsertionBars N
     *  Dependencies: StdDraw.java
     * 
     *  Insertion sort n random real numbers between 0 and 1, visualizing
     *  the results by ploting bars with heights proportional to the values.
     *
     *  % java InsertionBars 20
     *
     ******************************************************************************/


    public class InsertionBars {
        public static void sort(double[] a) {
            int n = a.length;
            for (int i = 0; i < n; i++) {
                int j = i;
                while (j >= 1 && less(a[j], a[j-1])) {
                    exch(a, j, j-1);
                    j--;
                }
                show(a, i, j);
            }
        }

        private static void show(double[] a, int i, int j) {
            StdDraw.setYscale(-a.length + i + 1, i);
            StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
            for (int k = 0; k < j; k++)
                StdDraw.line(k, 0, k, a[k]*0.6);
            StdDraw.setPenColor(StdDraw.BOOK_RED);
            StdDraw.line(j, 0, j, a[j]*0.6);
            StdDraw.setPenColor(StdDraw.BLACK);
            for (int k = j+1; k <= i; k++)
                StdDraw.line(k, 0, k, a[k]*0.6);
            StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
            for (int k = i+1; k < a.length; k++)
                StdDraw.line(k, 0, k, a[k]*0.6);
        }

        private static boolean less(double v, double w) {
            return v < w;
        }

        private static void exch(double[] a, int i, int j) {
            double t = a[i];
            a[i] = a[j];
            a[j] = t;
        }

        public static void main(String[] args) {
            int n = Integer.parseInt(args[0]);
            StdDraw.setCanvasSize(160, 640);
            StdDraw.setXscale(-1, n+1);
            StdDraw.setPenRadius(0.006);
            double[] a = new double[n];
            for (int i = 0; i < n; i++)
                a[i] = StdRandom.uniform(0.0, 1.0);
            sort(a);
        }

    }
    参考:教材官网。

  • 相关阅读:
    java web中使用log4j
    Apache Log4j配置说明
    sql数据库为null时候ASP语句判断问题
    js实现两个文本框数值的加减乘除运算
    js实现文本框支持加减运算的方法
    php报错syntax error, unexpected T_GOTO, expecting T_STRING,报错文件与行数指向以下代码,是什么原因?
    安装DEDECMS出现Function ereg_replace()错误的解决方法
    按钮显示隐藏div、input等
    设计input搜索框提示文字点击消失的效果
    Xcode export/upload error: Your session has expired. Please log in-b
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9860038.html
Copyright © 2011-2022 走看看