標籤:class bubble col == date 最大 資料 ... 標記
/** * 冒泡排序:Java * * @author skywang * @date 2014/03/11 */public class BubbleSort { /* * 冒泡排序 * * 參數說明: * a -- 待排序的數組 * n -- 數組的長度 */ public static void bubbleSort1(int[] a, int n) { int i,j; for (i=n-1; i>0; i--) { // 將a[0...i]中最大的資料放在末尾 for (j=0; j<i; j++) { if (a[j] > a[j+1]) { // 交換a[j]和a[j+1] int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } } /* * 冒泡排序(改進版) * * 參數說明: * a -- 待排序的數組 * n -- 數組的長度 */ public static void bubbleSort2(int[] a, int n) { int i,j; int flag; // 標記 for (i=n-1; i>0; i--) { flag = 0; // 添加一個標記,如果一趟遍曆中發生了交換,則標記為true,否則為false。如果某一趟沒有發生交換,說明排序已經完成! // 將a[0...i]中最大的資料放在末尾 for (j=0; j<i; j++) { if (a[j] > a[j+1]) { // 交換a[j]和a[j+1] int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; flag = 1; } } if (flag==0) break; // 退出演算法 } } public static void main(String[] args) { int i; int[] a = {20,40,30,10,60,50}; System.out.printf("before sort:"); for (i=0; i<a.length; i++) System.out.printf("%d ", a[i]); System.out.printf("\n"); bubbleSort1(a, a.length); //bubbleSort2(a, a.length); System.out.printf("after sort:"); for (i=0; i<a.length; i++) System.out.printf("%d ", a[i]); System.out.printf("\n"); }}
冒泡排序時間複雜度
冒泡排序的時間複雜度是O(N2)。
假設被排序的數列中有N個數。遍曆一趟的時間複雜度是O(N),需要遍曆多少次呢?N-1次!因此,冒泡排序的時間複雜度是O(N2)。
冒泡排序穩定性
冒泡排序是穩定的演算法,它滿足穩定演算法的定義。
演算法穩定性 -- 假設在數列中存在a[i]=a[j],若在排序之前,a[i]在a[j]前面;並且排序之後,a[i]仍然在a[j]前面。則這個排序演算法是穩定的!
轉載自 http://www.cnblogs.com/skywang12345/p/3596232.html
java冒泡排序