简析冒泡排序的算法

冒泡排序的基本思想是对比相邻元素值,如果满足条件就交换元素值,把较小的元素移动到数组前面,把大的元素移动到数组后面(也就是交换俩个元素的位置),这样数组元素就像气泡一样从底部上升到顶部。
冒泡算法在双层循环中实现,其中外层循环控制排序轮数,要排序数组长度减一。例如一个拥有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);
	}

}

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值