/**
* @param args
*/
public static void main(String[] args) {
int[] a = { 12, 2, 45, 23, 9, 88, 33, 23, 22, 5, 4, 4, 5, 1, 9, 7, 2,
7, 8, 0 };
ArraySort.bubbleSort(a);
}
/**
* 冒泡排序。從大到小排序。<br>
*
* @param source
* @return
*/
public static int[] bubbleSort(int[] source) {
boolean isSort = false; // 是否排序
for (int i = 1; i < source.length; i++) {
isSort = false; // 在每次排序前都初始化為false
for (int j = 0; j < source.length - i; j++) {
if (source[j] < source[j + 1]) {
int temp = source[j];
source[j] = source[j + 1];
source[j + 1] = temp;
isSort = true; // 為TRUE表明此次循環(外層循環)有排序。
}
}
if (!isSort)
break; // 如果沒有排序,說明數據已經排序完畢。
// 輸出每個子循環排序後的數組中的元素
printArray(source, i);
}
return source;
}
/**
* 循環輸出數組中的元素。
*
* @param a
* @param idx
* ,第壹層循環的index
*/
public static void printArray(int[] a,int idx) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + (i != a.length-1?",":""));
}
System.out.println("--idx:" + idx);
}
}