本文分享比較簡單的冒泡排序.
直接上乾貨.比較簡單,不做詳細說明.
package interview;
/**
* -冒泡排序
* @author
* @date
*/
public class BubbleSortTest {
private final static int[] arr = { 23, 40, 30, 59, 68, 11, 8 };
public static void main(String[] args) {
int len = arr.length,
temp = 0,
sum = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len-1-i; j++) {
//這裏注意 -i, 後面的循序已經排好,可以減少循環次數.
System.out.println("總循環次數: " + ++sum);
if(arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
System.out.print("j循環 ---> ");
sysOut(arr);
}
System.out.print("i循環 "+ i +"次===> ");
sysOut(arr);
}
}
private static void sysOut(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");;
}
System.out.println();
}
}
/*
.....
總循環次數: 20
j循環 ---> 11 8 23 30 40 59 68
i循環 4次===> 11 8 23 30 40 59 68
總循環次數: 21
j循環 ---> 8 11 23 30 40 59 68
i循環 5次===> 8 11 23 30 40 59 68
i循環 6次===> 8 11 23 30 40 59 68
*/
--end. 有問題請留言,謝謝.