今天突然被人问到冒泡排序怎么解决,一时之间自己竟然忘记了,不用也不记着笔记就是容易忘记,真是一件悲伤的事情!现在记着吧!
代码:
package com.paixu; /** * java实现冒泡排序 * * @author user * */ public class bubbleSort { /** * @param args */ public static void main(String[] args) { // 定义一个数组 int[] bubble = { 1, 4, 5, 7, 81, 23, 4, 46, 67, 98, 64, 33, 37, 99, 111, 23, 3, 298 }; // 定义一个临时变量作为交换数据使用 int temp; // 外层循环一次 for (int i = 0; i < bubble.length - 1; i++) { // 内层循环一遍 for (int j = i; j < bubble.length - i - 1; j++) { // 如果后面的数比前面的小,交换 if (bubble[j] > bubble[j + 1]) { temp = bubble[j]; bubble[j] = bubble[j + 1]; bubble[j + 1] = temp; } } System.out.print("第" + (i + 1) + "次排序结果:"); for (int m = 0; m < bubble.length; m++) { System.out.print(" "+bubble[m]+" "); } System.out.println(""); } } }
运行的结果:
第1次排序结果: 1 4 5 7 23 4 46 67 81 64 33 37 98 99 23 3 111 298
第2次排序结果: 1 4 5 7 4 23 46 67 64 33 37 81 98 23 3 99 111 298
第3次排序结果: 1 4 5 4 7 23 46 64 33 37 67 81 23 3 98 99 111 298
第4次排序结果: 1 4 5 4 7 23 46 33 37 64 67 23 3 81 98 99 111 298
第5次排序结果: 1 4 5 4 7 23 33 37 46 64 23 3 67 81 98 99 111 298
第6次排序结果: 1 4 5 4 7 23 33 37 46 23 3 64 67 81 98 99 111 298
第7次排序结果: 1 4 5 4 7 23 33 37 23 3 46 64 67 81 98 99 111 298
第8次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第9次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第10次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第11次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第12次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第13次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第14次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第15次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第16次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298
第17次排序结果: 1 4 5 4 7 23 33 23 3 37 46 64 67 81 98 99 111 298