用简单的java语言编写一个可动态输入无序数组,需打印每一趟的排序结果和有数据和UI图联动(数据同步)的冒泡排序算法
时间: 2024-02-06 07:09:20 浏览: 206
用Java写出冒泡排序的算法
以下是一个简单的Java代码实现冒泡排序算法,包括动态输入无序数组和打印每一趟排序结果。同时,使用Java Swing实现了UI界面,可以通过界面输入无序数组,并将排序结果实时显示在界面上。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BubbleSort extends JFrame implements ActionListener {
private JTextField inputField;
private JTextArea outputArea;
private JButton sortBtn;
public static void main(String[] args) {
BubbleSort frame = new BubbleSort();
frame.setVisible(true);
}
public BubbleSort() {
setTitle("Bubble Sort");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
JLabel inputLabel = new JLabel("Input an array of integers, separated by commas:");
inputField = new JTextField(20);
inputPanel.add(inputLabel);
inputPanel.add(inputField);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
sortBtn = new JButton("Sort");
sortBtn.addActionListener(this);
buttonPanel.add(sortBtn);
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BorderLayout());
JLabel outputLabel = new JLabel("Sorting Result:");
outputArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(outputArea);
outputPanel.add(outputLabel, BorderLayout.NORTH);
outputPanel.add(scrollPane, BorderLayout.CENTER);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.CENTER);
mainPanel.add(outputPanel, BorderLayout.SOUTH);
setContentPane(mainPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sortBtn) {
String input = inputField.getText();
String[] strArr = input.split(",");
int[] arr = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
arr[i] = Integer.parseInt(strArr[i].trim());
}
bubbleSort(arr);
}
}
private void bubbleSort(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
sb.append("Pass ").append(i + 1).append(": ");
for (int num : arr) {
sb.append(num).append(", ");
}
sb.delete(sb.length() - 2, sb.length() - 1);
sb.append("\n");
outputArea.setText(sb.toString());
}
}
}
```
阅读全文