冒泡排序可视化Java
时间: 2023-09-19 20:06:21 浏览: 95
冒泡排序 Java
以下是一个简单的冒泡排序可视化Java程序,使用Java Swing实现:
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BubbleSortVisualization extends JPanel {
private int[] data;
private int currIndex = 0;
private boolean isSorting = false;
private final int BAR_WIDTH = 10;
public BubbleSortVisualization(int[] arr) {
data = arr;
setPreferredSize(new Dimension(data.length * BAR_WIDTH, 300));
setBackground(Color.WHITE);
}
public void startSorting() {
isSorting = true;
new Thread(new Runnable() {
@Override
public void run() {
bubbleSort();
}
}).start();
}
private void bubbleSort() {
for (int i = 0; i < data.length - 1; i++) {
for (int j = 0; j < data.length - i - 1; j++) {
if (data[j] > data[j + 1]) {
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
currIndex = j + 1;
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
isSorting = false;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < data.length; i++) {
if (i == currIndex) {
g.setColor(Color.RED);
} else {
g.setColor(Color.BLUE);
}
g.fillRect(i * BAR_WIDTH, getHeight() - data[i], BAR_WIDTH, data[i]);
}
}
public static void main(String[] args) {
int[] data = new int[50];
Random rand = new Random();
for (int i = 0; i < data.length; i++) {
data[i] = rand.nextInt(200) + 1;
}
BubbleSortVisualization panel = new BubbleSortVisualization(data);
JFrame frame = new JFrame("Bubble Sort Visualization");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel.startSorting();
}
}
```
该程序使用随机生成的整数数组进行排序,每次交换两个元素时,会将当前正在交换的元素标为红色,其他元素标为蓝色。程序中使用了一个线程来执行排序,因为排序过程中需要暂停一段时间以实现可视化效果。在主函数中创建一个新的BubbleSortVisualization对象,并将其作为JFrame的内容面板。调用startSorting()方法开始排序,程序会自动执行冒泡排序并在界面上显示出来。
阅读全文