zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    (双指针 二分) leetcode 167. Two Sum II
    (双指针) leetcode 485. Max Consecutive Ones
    (双指针) leetcode 27. Remove Element
    (String) leetcode 67. Add Binary
    (数组) leetcode 66. Plus One
    (N叉树 BFS) leetcode429. N-ary Tree Level Order Traversal
    (N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal
    (N叉树 递归) leetcode589. N-ary Tree Preorder Traversal
    (N叉树 DFS 递归 BFS) leetcode 559. Maximum Depth of N-ary Tree
    (BST 递归) leetcode98. Validate Binary Search Tree
  • 原文地址:https://www.cnblogs.com/twodog/p/12135739.html
Copyright © 2011-2022 走看看