冒泡排序是在每次循环中将相邻的两个数字进行比较,最后,会把最大(最小)的数字放到最后一个,所以称之为冒泡-BubbleSort
如果有n个数字进行排序,在冒泡排序的过程中,最外层的循环次数n-1就是比较的躺数,内层循环即在每趟中进行n-i-1次比较
对于数组data,排序过程如下:
数组的长度为20
第0次排序:
[3, 3, 12, 32, 90, 123, 1, 2, 12, 3, 12, 3, 2, 32, 234, 1, 213, 1, 90, 313]
第1次排序:
[3, 3, 12, 32, 90, 1, 2, 12, 3, 12, 3, 2, 32, 123, 1, 213, 1, 90, 234, 313]
第2次排序:
[3, 3, 12, 32, 1, 2, 12, 3, 12, 3, 2, 32, 90, 1, 123, 1, 90, 213, 234, 313]
第3次排序:
[3, 3, 12, 1, 2, 12, 3, 12, 3, 2, 32, 32, 1, 90, 1, 90, 123, 213, 234, 313]
第4次排序:
[3, 3, 1, 2, 12, 3, 12, 3, 2, 12, 32, 1, 32, 1, 90, 90, 123, 213, 234, 313]
第5次排序:
[3, 1, 2, 3, 3, 12, 3, 2, 12, 12, 1, 32, 1, 32, 90, 90, 123, 213, 234, 313]
第6次排序:
[1, 2, 3, 3, 3, 3, 2, 12, 12, 1, 12, 1, 32, 32, 90, 90, 123, 213, 234, 313]
第7次排序:
[1, 2, 3, 3, 3, 2, 3, 12, 1, 12, 1, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第8次排序:
[1, 2, 3, 3, 2, 3, 3, 1, 12, 1, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第9次排序:
[1, 2, 3, 2, 3, 3, 1, 3, 1, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第10次排序:
[1, 2, 2, 3, 3, 1, 3, 1, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第11次排序:
[1, 2, 2, 3, 1, 3, 1, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第12次排序:
[1, 2, 2, 1, 3, 1, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第13次排序:
[1, 2, 1, 2, 1, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第14次排序:
[1, 1, 2, 1, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第15次排序:
[1, 1, 1, 2, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第16次排序:
[1, 1, 1, 2, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第17次排序:
[1, 1, 1, 2, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第18次排序:
[1, 1, 1, 2, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
第19次排序:
[1, 1, 1, 2, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
排序之后:
[1, 1, 1, 2, 2, 3, 3, 3, 3, 12, 12, 12, 32, 32, 90, 90, 123, 213, 234, 313]
==============================================
Process finished with exit code 0
代码:
package algorithmSort;
/**
* 冒泡排序
*/
public class BubbleSort {
public static void bubblesort(int[] data){
int arraylength=data.length;
System.out.println("数组的长度为"+arraylength);
for (int i = 0; i < arraylength; i++) {//第i次排序
for (int j = 0; j < arraylength - i-1; j++) {//从索引为j的数开始
if(data[j]>data[j+1]){
int temp=data[j+1];
data[j+1]=data[j];
data[j]=temp;
}
}
System.out.println("第"+i+"次排序:\n"+java.util.Arrays.toString(data));
}
}
public static void main(String[] args) {
int[] data = {3,12,3,90,32,234,123,1,2,12,3,12,3,2,32,313,1,213,1,90};
System.out.println("排序之前:\n"+java.util.Arrays.toString(data));
System.out.println("==============================================");
bubblesort(data);
System.out.println("排序之后:\n"+java.util.Arrays.toString(data));
System.out.println("==============================================");
}
}