冒泡排序算法的原理地球人都知道,在这儿就直接看代码吧。
package com.bin.test;
import java.util.Arrays;
/**
* 总结一下冒泡排序算法
* 1、双层循环实现;
* 2、依次找出最小值/最大值,找到最小值/最大值的就不要再比较了,提高效率;
* 3、第二层循环的循环变量初始值必须等于第一个变量或者第一个变量加1(加1会提高效率)
* @author haoyunlai
*
*/
public class Bubble {
public static void main(String[] args) {
//可以修改数组个数
int[] a = {3,78,2,5,0,56,43,12,98};
//为了不影响原始参数,排序时做一次copy
int[] b = Arrays.copyOf(a, a.length);
bubbleSort(b,b.length);
//打印排序结果
for(int k=0;k<b.length;k++){
System.out.println(b[k]);
}
}
/**
* 冒泡排序算法(从小到大)
* @param a
* @return
*/
private static void bubbleSort(int[] a,int length){
System.out.println("----start----");
int temp = 0;
for(int i=0;i<length;i++){
for(int j=(i+1);j<length;j++){//j=(i+1),not j=0
//用交换的方式,将小的数字放到前面
if(a[i]>a[j]){//改为a[i]<a[j]时实现从大到小排序
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
//每次排序的结果
for(int l=0;l<length;l++){
System.out.println("----" + a[l] + "----");
}
//输出完一次,打印分隔线
System.out.println("--------------------------");
}
System.out.println("----end ----");
}
}
打印结果:
----start----
----0----
----78----
----3----
----5----
----2----
----56----
----43----
----12----
----98----
--------------------------
----0----
----2----
----78----
----5----
----3----
----56----
----43----
----12----
----98----
--------------------------
----0----
----2----
----3----
----78----
----5----
----56----
----43----
----12----
----98----
--------------------------
----0----
----2----
----3----
----5----
----78----
----56----
----43----
----12----
----98----
--------------------------
----0----
----2----
----3----
----5----
----12----
----78----
----56----
----43----
----98----
--------------------------
----0----
----2----
----3----
----5----
----12----
----43----
----78----
----56----
----98----
--------------------------
----0----
----2----
----3----
----5----
----12----
----43----
----56----
----78----
----98----
--------------------------
----0----
----2----
----3----
----5----
----12----
----43----
----56----
----78----
----98----
--------------------------
----0----
----2----
----3----
----5----
----12----
----43----
----56----
----78----
----98----
--------------------------
----end ----
0
2
3
5
12
43
56
78
98