简析冒泡排序的算法

冒泡排序的基本思想是对比相邻元素值,如果满足条件就交换元素值,把较小的元素移动到数组前面,把大的元素移动到数组后面(也就是交换俩个元素的位置),这样数组元素就像气泡一样从底部上升到顶部。
冒泡算法在双层循环中实现,其中外层循环控制排序轮数,要排序数组长度减一。例如一个拥有6个元素的数组,在排序过程中每次循环的排序过程和结果如图所示
在这里插入图片描述设计代码如下:

package mytext;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

import javax.swing.*;
;

public class Text50 extends JFrame {
	 public JTextArea text1,text2;
	 public JButton button1,button2;
	 public FlowLayout layout1;
	 public int array[]=new int[10];
	public Text50() {
		setLayout(new FlowLayout());
		
		text1=new JTextArea();
		text2=new JTextArea();
		button1=new JButton();
		button2=new JButton();
		text1.setBounds(30,60,50,50);
		text2.setBounds(80,110,50,50);
		button1.setText("生成随机数");
		button2.setText("生成冒泡排序序列");
		add(text1);
		add(button1);
		add(text2);
		add(button2);
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			Random random=new Random();
			text1.setText("");
			for(int i=0;i<array.length;i++) {
				array[i]=random.nextInt(100);
				text1.append(array[i]+" ");
				}	
			}
		
		});
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				text2.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;
						}
						text2.append(array[j]+" ");
					}
					text2.append("【");
					for(int j=array.length-i;j<array.length;j++) {
						text2.append(array[j]+" ");
					}
					text2.append("】\n");
				}	
			}
		});
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Text50 t=new Text50();
		t.setBounds(100,100,290,282);
		t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		t.setVisible(true);
	}

}

结果如图
在这里插入图片描述

发布了8 篇原创文章 · 获赞 3 · 访问量 5174

猜你喜欢

转载自blog.csdn.net/s56564/article/details/104676912