冒泡排序

冒泡排序就是像煮开水那样,大的气泡先向上浮,大的值排在前面。

package book;

public class JiOu {
	public static void main(String[] args) {
		/*
		 * 冒泡排序
		 */
		int score[] = { 12, 73, 25, 66, 99 }; // 声明数组并赋值
		for (int i = 0; i < score.length - 1; i++) { // 循环n-1次
			for (int j = i + 1; j < score.length; j++) { // 比较排序
				if (score[i] < score[j]) {
					int temp = score[i]; // 设定中间值temp
					score[i] = score[j]; // 大的往前排
					score[j] = temp; // 小的往后排
				}
			}
			System.out.print("第" + (i + 1) + "次排序:"); // 观察每次排序的结果
			for (int j = 0; j < score.length; j++) {
				System.out.print(score[j] + "  ");
			}
			System.out.println("  ");
		}
		for (int i = 0; i < score.length; i++) { // 输出最后的排序结果
			System.out.println(score[i]);
		}
	}
}

运行结果为:

第1次排序:99  12  25  66  73    
第2次排序:99  73  12  25  66    
第3次排序:99  73  66  12  25    
第4次排序:99  73  66  25  12    
99
73
66
25
12

修改一下,可以从键盘输入数组再排序:

package book;

import java.util.Scanner;

public class JiOu {
	public static void main(String[] args) {
		/*
		 * 冒泡排序
		 */
		System.out.println("请输入数组的大小:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] score = new int[n];
		System.out.println("请输入数组的每个元素:");
		for (int i = 0; i < score.length; i++) {
			score[i] = sc.nextInt();
		}
		sc.close();
		for (int i = 0; i < score.length - 1; i++) { // 循环n-1次
			for (int j = i + 1; j < score.length; j++) { // 比较排序
				if (score[i] < score[j]) {
					int temp = score[i]; // 设定中间值temp
					score[i] = score[j]; // 大的往前排
					score[j] = temp; // 小的往后排
				}
			}
			System.out.print("第" + (i + 1) + "次排序:"); // 观察每次排序的结果
			for (int j = 0; j < score.length; j++) {
				System.out.print(score[j] + "  ");
			}
			System.out.println("  ");
		}
		for (int i = 0; i < score.length; i++) { // 输出最后的排序结果
			System.out.println(score[i]);
		}
	}
}

其中一个运行结果:

请输入数组的大小:
5
请输入数组的每个元素:
66 55 89 12 37
第1次排序:89  55  66  12  37    
第2次排序:89  66  55  12  37    
第3次排序:89  66  55  12  37    
第4次排序:89  66  55  37  12    
89
66
55
37
12

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值