1. 程式人生 > >java插入排序視覺化

java插入排序視覺化

工具類

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

import java.lang.InterruptedException;

public class AlgoVisHelper {

    private AlgoVisHelper(){}

    public static final Color Red = new Color(0xF44336);
    public static final Color Pink = new Color(0xE91E63);
    public static
final Color Purple = new Color(0x9C27B0); public static final Color DeepPurple = new Color(0x673AB7); public static final Color Indigo = new Color(0x3F51B5); public static final Color Blue = new Color(0x2196F3); public static final Color LightBlue = new Color(0x03A9F4); public static final
Color Cyan = new Color(0x00BCD4); public static final Color Teal = new Color(0x009688); public static final Color Green = new Color(0x4CAF50); public static final Color LightGreen = new Color(0x8BC34A); public static final Color Lime = new Color(0xCDDC39); public static final Color Yellow = new
Color(0xFFEB3B); public static final Color Amber = new Color(0xFFC107); public static final Color Orange = new Color(0xFF9800); public static final Color DeepOrange = new Color(0xFF5722); public static final Color Brown = new Color(0x795548); public static final Color Grey = new Color(0x9E9E9E); public static final Color BlueGrey = new Color(0x607D8B); public static final Color Black = new Color(0x000000); public static final Color White = new Color(0xFFFFFF); public static void strokeCircle(Graphics2D g, int x, int y, int r){ Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r); g.draw(circle); } public static void fillCircle(Graphics2D g, int x, int y, int r){ Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r); g.fill(circle); } public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h){ Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h); g.draw(rectangle); } public static void fillRectangle(Graphics2D g, int x, int y, int w, int h){ Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h); g.fill(rectangle); } public static void setColor(Graphics2D g, Color color){ g.setColor(color); } public static void setStrokeWidth(Graphics2D g, int w){ int strokeWidth = w; g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); } public static void pause(int t) { try { Thread.sleep(t); } catch (InterruptedException e) { System.out.println("Error sleeping"); } } public static void putImage(Graphics2D g, int x, int y, String imageURL){ ImageIcon icon = new ImageIcon(imageURL); Image image = icon.getImage(); g.drawImage(image, x, y, null); } public static void drawText(Graphics2D g, String text, int centerx, int centery){ if(text == null) throw new IllegalArgumentException("Text is null in drawText function!"); FontMetrics metrics = g.getFontMetrics(); int w = metrics.stringWidth(text); int h = metrics.getDescent(); g.drawString(text, centerx - w/2, centery + h); } }

資料層

import java.util.Arrays;


public class InsertionSortData {

    public enum Type{
        //正常資料
        Default, 
        //近乎有序的資料
        NearlyOrdered
    }

    private int[] numbers;
    public int orderedIndex;           // [0...orderedIndex) 是有序的
    public int currentIndex;

    public InsertionSortData(int N, int randomBound, Type dataType){

        numbers = new int[N];

        for( int i = 0 ; i < N ; i ++)
            numbers[i] = (int)(Math.random()*randomBound) + 1;
        //判斷是否使用近乎有序的資料
        if(dataType == Type.NearlyOrdered){
            //進行排序
            Arrays.sort(numbers);
            //使百分之2的資料混亂
            int swapTime = (int)(0.02*N);
            for(int i = 0 ; i < swapTime; i ++){
                int a = (int)(Math.random()*N);
                int b = (int)(Math.random()*N);
                swap(a, b);
            }
        }
    }

    public InsertionSortData(int N, int randomBound){
        this(N, randomBound, Type.Default);
    }

    public int N(){
        return numbers.length;
    }

    public int get(int index){
        if( index < 0 || index >= numbers.length)
            throw new IllegalArgumentException("Invalid index to access Sort Data.");

        return numbers[index];
    }
    //交換資料
    public void swap(int i, int j) {
        if( i < 0 || i >= numbers.length || j < 0 || j >= numbers.length)
            throw new IllegalArgumentException("Invalid index to access Sort Data.");

        int t = numbers[i];
        numbers[i] = numbers[j];
        numbers[j] = t;
    }
}

檢視層

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class AlgoFrame extends JFrame{

    private int canvasWidth;
    private int canvasHeight;

    public AlgoFrame(String title, int canvasWidth, int canvasHeight){

        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        AlgoCanvas canvas = new AlgoCanvas();
        setContentPane(canvas);
        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
    }

    public AlgoFrame(String title){

        this(title, 1024, 768);
    }

    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}

    // data
    private InsertionSortData data;
    public void render(InsertionSortData data){
        this.data = data;
        repaint();
    }

    private class AlgoCanvas extends JPanel{

        public AlgoCanvas(){
            // 雙快取
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D)g;

            // 抗鋸齒
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.addRenderingHints(hints);

            // 具體繪製
            int w = canvasWidth/data.N();
            for(int i = 0 ; i < data.N() ; i ++ ) {
                //判斷當前索引是否以排序
                if (i < data.orderedIndex)
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);
                else
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Grey);
                //判斷是否當前索引資料
                if( i == data.currentIndex )
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                //繪製
                AlgoVisHelper.fillRectangle(g2d, i * w, canvasHeight - data.get(i), w - 1, data.get(i));
            }
        }

        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

效果圖

正常資料與幾乎有序資料插入排序效率對比

這裡寫圖片描述
在近乎有序的資料插入排序可“進化”為O(n)的演算法