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

作者:天人合一peng 时间:2021-08-06 19:35:50 

参考文章

图解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);
   }
}

来源:https://blog.csdn.net/moonlightpeng/article/details/126497005

标签:Java,插入,排序
0
投稿

猜你喜欢

  • JAVA简单工厂模式(从现实生活角度理解代码原理)

    2021-10-29 12:39:32
  • SpringTask实现定时任务方法讲解

    2022-06-11 11:43:42
  • Mybatis工具类JdbcTypeInterceptor运行时自动添加jdbcType属性

    2023-08-24 03:49:59
  • C#使用Json.Net对JSON与对象的序列化与反序列化

    2023-04-08 07:22:25
  • maven的pom文件与打包详解

    2023-12-24 00:23:51
  • Java有趣好玩的图形界面开发八个案例实现

    2022-12-20 06:20:35
  • Java Web项目中解决中文乱码方法总结(三种最新方法)

    2023-07-18 18:13:22
  • SpringCloud用Zookeeper搭建配置中心的方法

    2022-12-17 18:16:18
  • java 值Document解析xml详细介绍

    2021-11-13 15:59:00
  • 解决MyBatis @param注解参数类型错误异常的问题

    2023-12-01 06:41:45
  • 分析SpringBoot的启动原理

    2021-10-30 16:01:23
  • springcloud-gateway整合jwt+jcasbin实现权限控制的详细过程

    2023-11-20 12:57:09
  • C#可用于登录验证码的四位随机数生成方法

    2021-08-01 00:31:01
  • Spring中集成Groovy的四种方式(小结)

    2023-07-11 16:36:53
  • 在c#中使用servicestackredis操作redis的实例代码

    2022-06-23 14:28:48
  • mybatis水平分表实现动态表名的项目实例

    2023-04-02 22:11:42
  • iOS新浪微博、腾讯微博分享功能实例

    2023-06-16 09:15:53
  • SpringBoot自定义Starter实现流程详解

    2022-05-19 07:03:25
  • 流读取导致StringBuilder.toString()乱码的问题及解决

    2022-12-20 13:34:14
  • 关于LinkedList集合对元素进行增查删操作

    2022-09-23 11:48:45
  • asp之家 软件编程 m.aspxhome.com