冒泡排序就是像煮开水那样,大的气泡先向上浮,大的值排在前面。
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