使用冒泡排序法

来源:互联网 发布:新概念英语网络课程 编辑:程序博客网 时间:2024/06/10 11:39
package san;


import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;


public class BubbleSort extends JFrame {


private JPanel contentPane;
private JTextArea textArea;
private JTextArea textArea_1;





/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BubbleSort frame = new BubbleSort();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


/**
* Create the frame.
*/
public BubbleSort() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 600);
setTitle("冒泡排序算法");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);


   textArea = new JTextArea();
textArea.setBounds(34, 23, 376, 31);
contentPane.add(textArea);

JButton btnNewButton = new JButton("\u751F\u6210\u968F\u673A\u6570");
btnNewButton.setBounds(145, 64, 157, 31);
contentPane.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_btnNewButton_actionPerformed(e);
}
});





textArea_1 = new JTextArea();
textArea_1.setBounds(34, 105, 376, 383);
contentPane.add(textArea_1);






JButton button = new JButton("\u5192\u6CE1\u6392\u5E8F\u7B97\u6CD5");
button.setBounds(145, 498, 157, 31);
contentPane.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_button_actionPerformed(e);
}
});



}

private int[] array=new int[10];

protected void do_btnNewButton_actionPerformed(ActionEvent e){

textArea.setText("  ");

for(int i=0;i<array.length;i++){
Random random=new Random();
array[i]=random.nextInt(50);

textArea.append(array[i]+" ");

}

}

protected void do_button_actionPerformed(ActionEvent e){

textArea_1.setText("");

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

for(int j=0;j<array.length-i;j++){
if(array[j]>array[j+1]){
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;




}
textArea_1.append(array[j]+" ");


}
textArea_1.append("【");
for(int j=array.length-i;j<array.length;j++){
textArea_1.append( array[j]+" ");


}
textArea_1.append( "】\n");


}




}



}


结果:




















原创粉丝点击