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


猜你喜欢
- 这几年一直在做手机上和电视盒的App,几乎没有考虑过横竖屏切换的问题。电视盒好说,横屏不变,你要是给它设计个竖屏人家也没机会使;而手机上的应
- 写下来自己以后看:先是item的布局文件:里边放了一个图片和一个文本框<?xml version="1.0" en
- 本文介绍了使用C#创建Windows服务的实例代码,分享给大家一、开发环境操作系统:Windows 10 X64开发环境:VS2015编程语
- Android基础教程数据存储之文件存储将数据存储到文件中并读取数据1、新建FilePersistenceTest项目,并修改activit
- 这篇文章主要介绍了简单了解Java中的可重入锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参
- mybatis-plus想要修改某字段为null问题场景使用mybatis + mybatisPlus进行修改某字段,想要将其设为null,
- ①概念二叉搜索树又称二叉排序树,它或者是一棵空树**,或者是具有以下性质的二叉树:若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
- 一、前言正常情况下classloader只能找到jar里面当前目录或者文件类里面的*.class文件。为了能够加载嵌套jar里面的资源之前都
- 出处:https://www.cnblogs.com/SunSpringeclipse下面创建的Maven项目,使用mybatis。ecli
- 前言 随着Java生态愈发庞大,各种各样的新技术层出不穷,这也给大家的学习带来了很多困惑,这么多技术我该学什么,盲目的在各种新技术间
- 题目:打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身
- 关于jmeter中的正则表达式及json提取器可以提取响应值,大家都有所了解,但是往往我们在实际运用中,可能需要上个接口的多个响应值,难道我
- Radiobutton是一种单选按钮,是由于RadioGroup管理下的一组按钮,所以一旦其中的一个button选中,再点击,就不能取消,想
- 一、序言Java多线程编程线程池被广泛使用,甚至成为了标配。线程池本质是池化技术的应用,和连接池类似,创建连接与关闭连接属于耗时操作,创建线
- 为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性
- Spring2.5.6开发环境搭建的过程,供大家参考,具体内容如下1、jar 包准备:spring 2.5.6 的 jar 包(链接: ht
- Interface Segregation Principle,ISP接口隔离原则主张使用多个专门的接口比使用单一的总接口要好。一个类对另外
- 前言今天看到某一篇文章的一句话 单例DCL 前面加 V 。就这句话让我把 单例模式 又仔细看了一遍。Java
- 因项目集成了Redis缓存部分数据,需要在程序启动时将数据加载到Redis中,即初始化数据到Redis。在SpringBoot项目下,即在容
- class文件中的常量池之前我们在讲class文件的结构时,提到了每个class文件都有一个常量池,常量池中存了些什么东西呢?字符串常量,类