package com.cnse.arraySort; /** * @inof 冒泡排序 * @author kxw */ public class BubbleSort { public static void main(String[] args) { int[] ary = { 3, 1, 4, 6, 8, 9, 2, 5, 7 }; for (int i = 0; i < ary.length - 1; i++) { // for (int i = 0; i < 9; i++) { //替換i<X方便測試 for (int j = 0; j < ary.length - 1 - i; j++) { if (ary[j] > ary[j + 1]) { int t = ary[j]; ary[j] = ary[j + 1]; ary[j + 1] = t; } } System.out.print((i + 1) + ",次" + "\n"); } for (int i = 0; i < ary.length; i++) { System.out.print(ary[i] + "__"); } } } /** * 1 2 3 4 5 2和1比較 3和2比較 n+1 和n比較 */ /** * 1,次 1__3__4__6__8__2__5__7__9__ */ /** * 2,次 1__3__4__6__2__5__7__8__9__ */ /** * 3,次 1__3__4__2__5__6__7__8__9__ */ /** * 4,次 1__3__2__4__5__6__7__8__9__ */ /** * 5,次 ===已經排序完成 1__2__3__4__5__6__7__8__9__ */ /** * 6,次 1__2__3__4__5__6__7__8__9__ */ /** * 7,次 1__2__3__4__5__6__7__8__9__ */ /** * 8,次 1__2__3__4__5__6__7__8__9__ */ /** * 9,次 1__2__3__4__5__6__7__8__9__ */ /** * @author http://www.oschina.net/code/snippet_2634485_54061 * @info 莫娜 */ class AnOtherBubble_sort { public static void main(String[] args) { int a[] = { 25, 68, 59, 78, 45, 32, 1, 9, 47, 43, 196 }; System.out.println("排序前:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ","); } System.out.println("\n排序後:"); for (int i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) { if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } System.out.print(i + "次,"); } for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "__"); } } } /** 排序前: 25,68,59,78,45,32,1,9,47,43,196, 排序後: 0次, 1次, 2次, 3次, 4次, 5次, 6次, 7次, 8次, 9次, 10次, 1__9__25__32__43__45__47__59__68__78__196__ **/