Java 冒泡排序可视化
时间: 2023-09-19 14:06:23 浏览: 88
下面是Java实现的冒泡排序可视化示例代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BubbleSortVisualization extends JPanel {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int MAX_VALUE = 500;
private static final int BAR_WIDTH = 5;
private int[] arr;
private int i, j;
public BubbleSortVisualization() {
arr = new int[WIDTH / BAR_WIDTH];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(MAX_VALUE);
}
i = 0;
j = 0;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
for (int k = 0; k < arr.length; k++) {
g.fillRect(k * BAR_WIDTH, HEIGHT - arr[k], BAR_WIDTH, arr[k]);
}
if (i < arr.length) {
if (j < arr.length - i - 1) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
j++;
} else {
i++;
j = 0;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bubble Sort Visualization");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
BubbleSortVisualization panel = new BubbleSortVisualization();
frame.add(panel);
frame.setVisible(true);
while (true) {
panel.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
该程序使用 `JFrame` 和 `JPanel` 组件实现了一个窗口,将一个数组的值以柱状图的形式可视化出来。在 `paintComponent` 方法中,使用 `Graphics` 绘图类将数组中的值绘制成柱状图,并通过 `i` 和 `j` 变量控制冒泡排序的过程,每次交换两个相邻的元素。在 `main` 方法中,使用线程不断重绘窗口,实现动画效果。
阅读全文