排序算法 - 冒泡排序算法 - 冒泡排序算法示例
最编程
2024-04-19 07:36:33
...
根据上面的基本的思想,我们来动手写一个例子说明冒泡排序在排序中的应用。
package Bubble;
public class BubbleAlgorithm {
public static void bunnle(int[] a){
int temp;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length-1; j++) {
if (a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j] = temp;
}
}
System.out.print("第"+i+"步排序结果:");
for (int k = 0; k < a.length; k++) {
System.out.print(" "+a[k]);
}
System.out.println("\n");
}
}
public static void main(String[] args) {
int[] aa = {196,182,123,104,111,106,185,194,192,159};
System.out.print(" 初始值:");
for (int i = 0; i < aa.length ; i++) {
System.out.print(" "+aa[i]);
}
System.out.println("\n");
bunnle(aa);
}
}
运行结果如下:
初始值: 196 182 123 104 111 106 185 194 192 159
第1步排序结果: 182 123 104 111 106 185 194 192 159 196
第2步排序结果: 123 104 111 106 182 185 192 159 194 196
第3步排序结果: 104 111 106 123 182 185 159 192 194 196
第4步排序结果: 104 106 111 123 182 159 185 192 194 196
第5步排序结果: 104 106 111 123 159 182 185 192 194 196
第6步排序结果: 104 106 111 123 159 182 185 192 194 196
第7步排序结果: 104 106 111 123 159 182 185 192 194 196
第8步排序结果: 104 106 111 123 159 182 185 192 194 196
第9步排序结果: 104 106 111 123 159 182 185 192 194 196
图中显示了每一步排序的中间结果。从中可以看出第5步之后便已经完成对数据的排序,但是算法仍然需要进行后续的比较步骤。根据上面介绍的思路,加入判断部分,使之能够尽早结束排序过程,从而提高程序的执行效率。调优方法如下:
package Bubble;
public class BubbleAlgorithm {
public static void bunnle(int[] a){
int temp;
//定义
int fay = 0;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length-1; j++) {
if (a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.print("第"+i+"步排序结果:");
for (int k = 0; k < a.length; k++) {
//开始
if (a.length-2 >= k){
if (a[k]>a[k+1]){
fay = 1;
}
}
//结束
System.out.print(" "+a[k]);
}
//开始
if (fay == 0){
break;
}else {
fay = 0;
}
//结束
System.out.println("\n");
}
}
public static void main(String[] args) {
int[] aa = {196,182,123,104,111,106,185,194,192,159};
System.out.print(" 初始值:");
for (int i = 0; i < aa.length ; i++) {
System.out.print(" "+aa[i]);
}
System.out.println("\n");
bunnle(aa);
}
}
输出结果如下:
初始值: 196 182 123 104 111 106 185 194 192 159
第1步排序结果: 182 123 104 111 106 185 194 192 159 196
第2步排序结果: 123 104 111 106 182 185 192 159 194 196
第3步排序结果: 104 111 106 123 182 185 159 192 194 196
第4步排序结果: 104 106 111 123 182 159 185 192 194 196
第5步排序结果: 104 106 111 123 159 182 185 192 194 196