Java冒泡排序+图形界面显示 运算步骤

importjava.awt.FlowLayout;

importjava.awt.TextArea;

importjava.awt.event.ActionEvent;

importjava.awt.event.ActionListener;

 

importjavax.swing.JButton;

importjavax.swing.JFrame;

 

public class Test9 extends JFrame{

private JButtonbtn = new JButton("排序");

private static TextArea ta = new TextArea(12,70);

private int[] arr ={2,1,6,88,12,99,12,33,99,88,100,22,-7};;

public Test9() {

setSize(550, 300);

setVisible(true);

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

setLocationRelativeTo(null);

setLayout(new FlowLayout());

add(btn);

btn.addActionListener(new ActionListener() {

 

publicvoid actionPerformed(ActionEvent arg0) {

bubbleSort(arr);

}

});

add(ta);

}

/**

* @param args

*/

public static void main(String[] args) {

new Test9();

}

 

public static int[] bubbleSort(int[] source) {

boolean isSort =false; // 是否排序

 

for (int i = 1; i < source.length; i++) {

isSort = false;// 在每次排序前都初始化为false

 

ta.append("---------------"+i+"次排序【"+arrayToString(source)+"---------------\n");

 

for (int j = 0; j < source.length - i; j++) {

if (source[j] > source[j + 1]) {

int temp = source[j];

source[j]= source[j + 1];

source[j+ 1] = temp;

 

isSort= true;// TRUE表明此次循环(外层循环)有排序。

 

ta.append("" + i +"次排序,第" + (j+1) +"次比较。" + source[j] +"" + source[j+1] +"交换位置【"+arrayToString(source)+"\n");

}

}

 

if (!isSort) {

ta.append("排序完毕!\n");

break;// 如果没有排序,说明数据已经排序完毕。

}

}

return source;

}

 

public static String arrayToString(int[] arr) {

if (arr ==null || arr.length == 0) {

return"";

}

StringBuilder sbr = new StringBuilder();

 

for (int i=0;i<arr.length;i++) {

sbr.append(arr[i]);

if (i != arr.length - 1) {

sbr.append(",");

}

}

 

return sbr.toString();

}

}

 

Java冒泡排序+图形界面显示 运算步骤

你可能感兴趣的:(java)