java swing 冒泡排序 实时 显示 演示
时间: 2023-09-12 08:07:47 浏览: 131
冒泡排序算法的动态演示程序
3星 · 编辑精心推荐
好的,我可以为您演示一个 Java Swing 冒泡排序实时显示的程序。以下是程序的代码:
```java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BubbleSortVisualizer extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JButton button;
private JTextField textField;
private int[] array = { 5, 3, 1, 2, 4 };
private int delay = 500;
public BubbleSortVisualizer() {
setTitle("Bubble Sort Visualizer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setResizable(false);
panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
panel.add(topPanel, BorderLayout.NORTH);
JLabel label = new JLabel("Array: ");
topPanel.add(label);
textField = new JTextField(20);
textField.setEditable(false);
topPanel.add(textField);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
panel.add(bottomPanel, BorderLayout.SOUTH);
button = new JButton("Sort");
bottomPanel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread thread = new Thread(new Runnable() {
public void run() {
bubbleSort();
}
});
thread.start();
}
});
setVisible(true);
}
private void bubbleSort() {
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
updateTextField();
sleep();
}
}
}
}
private void updateTextField() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < array.length; i++) {
stringBuilder.append(array[i]);
if (i != array.length - 1) {
stringBuilder.append(", ");
}
}
textField.setText(stringBuilder.toString());
}
private void sleep() {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new BubbleSortVisualizer();
}
}
```
运行程序后,您可以在窗口中看到一个文本框和一个“Sort”按钮。文本框显示了初始数组的值(即 `5, 3, 1, 2, 4`)。当您点击“Sort”按钮时,程序将开始使用冒泡排序对数组进行排序,并在每次交换时更新文本框中的值,以实现实时演示。程序默认的延迟时间为 500 毫秒,您可以根据需要更改此值。
阅读全文