Java实现插入排序算法可视化的示例代码

 更新时间:2022年08月24日 09:26:15   作者:天人合一peng  
插入排序的算法描述是一种简单直观的排序算法。其原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。本文将用Java语言实现插入排序算法并进行可视化,感兴趣的可以了解一下

参考文章

图解Java中插入排序算法的原理与实现

实现效果

示例代码

import java.awt.*;
 
public class AlgoVisualizer {
 
    private static int DELAY = 40;
 
    private InsertionSortData data;
    private AlgoFrame frame;
 
    public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){
 
        // 初始化数据
        data = new InsertionSortData(N, sceneHeight);
 
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Insertion Sort Visualization", sceneWidth, sceneHeight);
 
            new Thread(() -> {
                run();
            }).start();
        });
    }
 
    public void run(){
 
        setData(0, -1);
 
        for( int i = 0 ; i < data.N() ; i ++ ){
 
            setData(i, i);
            for(int j = i ; j > 0 && data.get(j) < data.get(j-1) ; j --){
                data.swap(j,j-1);
                setData(i+1, j-1);
            }
        }
        setData(data.N(), -1);
 
    }
 
    private void setData(int orderedIndex, int currentIndex){
        data.orderedIndex = orderedIndex;
        data.currentIndex = currentIndex;
 
        frame.render(data);
        AlgoVisHelper.pause(DELAY);
    }
 
    public static void main(String[] args) {
 
        int sceneWidth = 800;
        int sceneHeight = 800;
        int N = 100;
 
        AlgoVisualizer vis = new AlgoVisualizer(sceneWidth, sceneHeight, N);
    }
}
import java.awt.*;
import javax.swing.*;
 
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();
            //AlgoVisHelper.setColor(g2d, AlgoVisHelper.Grey);
            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.Green);
                AlgoVisHelper.fillRectangle(g2d, i * w, canvasHeight - data.get(i), w - 1, data.get(i));
            }
        }
 
        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}
 
public class InsertionSortData {
 
    private int[] numbers;
    public int orderedIndex = -1;   // [0...orderedIndex) 是有序的
    public int currentIndex = -1;
 
    public InsertionSortData(int N, int randomBound){
 
        numbers = new int[N];
 
        for( int i = 0 ; i < N ; i ++)
            numbers[i] = (int)(Math.random()*randomBound) + 1;
    }
 
    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 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);
    }
}

到此这篇关于Java实现插入排序算法可视化的示例代码的文章就介绍到这了,更多相关Java插入排序内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java音频播放示例分享(java如何播放音频)

    java音频播放示例分享(java如何播放音频)

    java如何播放音频?下面的代码就介绍了java音频播放示例,需要的朋友可以参考下
    2014-04-04
  • Java中常见的查找算法与排序算法总结

    Java中常见的查找算法与排序算法总结

    数据结构是数据存储的方式,算法是数据计算的方式。所以在开发中,算法和数据结构息息相关。本文为大家整理了Java中常见的查找与排序算法的实现,需要的可以参考一下
    2023-03-03
  • 新手入门Jvm--Jvm垃圾回收

    新手入门Jvm--Jvm垃圾回收

    JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的
    2021-06-06
  • JavaWeb 入门篇:创建Web项目,Idea配置tomcat

    JavaWeb 入门篇:创建Web项目,Idea配置tomcat

    这篇文章主要介绍了IDEA创建web项目配置Tomcat的详细教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-07-07
  • Springboot AOP对指定敏感字段数据加密存储的实现

    Springboot AOP对指定敏感字段数据加密存储的实现

    本篇文章主要介绍了利用Springboot+AOP对指定的敏感数据进行加密存储以及对数据中加密的数据的解密的方法,代码详细,具有一定的价值,感兴趣的小伙伴可以了解一下
    2021-11-11
  • 详解spring+springmvc+mybatis整合注解

    详解spring+springmvc+mybatis整合注解

    本篇文章主要介绍了详解spring+springmvc+mybatis整合注解,详细的介绍了ssm框架的使用,具有一定的参考价值,有兴趣的可以了解一下
    2017-04-04
  • Java RabbitMQ的TTL和DLX全面精解

    Java RabbitMQ的TTL和DLX全面精解

    过期时间TTL表示可以对消息设置预期的时间,在这个时间内都可以被消费者接收获取;过了之后消息将自动被删除。DLX, 可以称之为死信交换机,当消息在一个队列中变成死信之后,它能被重新发送到另一个交换机中,这个交换机就是DLX ,绑定DLX的队列就称之为死信队列
    2021-09-09
  • java Arrays类详解及实例代码

    java Arrays类详解及实例代码

    这篇文章主要介绍了java Arrays类详解及实例代码的相关资料,需要的朋友可以参考下
    2016-10-10
  • Java中抽象类的作用及说明

    Java中抽象类的作用及说明

    这篇文章主要介绍了Java中抽象类的作用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • 如何解决Springboot Dao注入失败的问题

    如何解决Springboot Dao注入失败的问题

    这篇文章主要介绍了如何解决Spring boot Dao注入失败的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05

最新评论