001package algs21;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac ZSelectionBars.java
005 *  Execution:    java ZSelectionBars N
006 *  Dependencies: StdDraw.java
007 *
008 *  Selection sort N random real numbers between 0 and 1, visualizing
009 *  the results by ploting bars with heights proportional to the values.
010 *
011 *  % java ZSelectionBars 20
012 *
013 *************************************************************************/
014
015public class XBarsSelection {
016
017        public static void sort(double[] a) {
018                int N = a.length;
019                for (int i = 0; i < N; i++) {
020                        int min = i;
021                        for (int j = i+1; j < N; j++)
022                                if (less(a[j], a[min])) min = j;
023                        show(a, i, min);
024                        exch(a, i, min);
025                }
026        }
027
028        private static void show(double[] a, int i, int min) {
029                StdDraw.setYscale(-a.length + i + 1, i);
030                StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
031                for (int k = 0; k < i; k++)
032                        StdDraw.line(k, 0, k, a[k]*.6);
033                StdDraw.setPenColor(StdDraw.BLACK);
034                for (int k = i; k < a.length; k++)
035                        StdDraw.line(k, 0, k, a[k]*.6);
036                StdDraw.setPenColor(StdDraw.BOOK_RED);
037                StdDraw.line(min, 0, min, a[min]*.6);
038        }
039
040        private static boolean less(double v, double w) {
041                return v < w;
042        }
043
044        private static void exch(double[] a, int i, int j) {
045                double t = a[i]; a[i] = a[j]; a[j] = t;
046        }
047
048        public static void main(String[] args) {
049                args = new String[] { "10" };
050                int N = Integer.parseInt(args[0]);
051                StdDraw.setCanvasSize(N*8, N*32);
052                StdDraw.setXscale(-1, N+1);
053                StdDraw.setPenRadius(.006);
054                sort (ArrayGenerator.doubleRandomUnique (N));
055                //sort (ArrayGenerator.partiallySortedUnique (N));
056                //sort (ArrayGenerator.sortedUnique (N));
057                //sort (ArrayGenerator.reverseSortedUnique (N));
058        }
059
060}