日期:2014-05-20 浏览次数:20931 次
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sort extends JFrame {
JButton output;
JTextField input;
JTextArea outnum;
String s;
public Sort() {
super("排序");
setSize(500, 100);
setLocation(300, 300);
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER));
input = new JTextField(24);
output = new JButton("排序");
output.addActionListener(new SortHandler());
outnum = new JTextArea(1, 30);
outnum.setBackground(Color.cyan);
c.add(input);
c.add(output);
c.add(outnum);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Sort();
}
public void sortFun(String[] a, int n) {
try {
for (int x = 0; x < n; x++) {
int temp, z;
temp = Integer.parseInt(a[x]);
z = x - 1;
while (z >= 0 && temp < Integer.parseInt(a[z])) {//这里从0开始
a[z + 1] = a[z];
a[z]=String.valueOf(temp);//这里实现互换
z--;
}
//a[z + 1] = a[z];这里不需要这样
}
for (int i = 0; i < n; i++)
outnum.append(a[i] + " ");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public class SortHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == output) {
outnum.setText("");
String string = input.getText();
String[] str = string.split(" ");
int sum = str.length;
sortFun(str, sum);
}
}
}
}