氣泡排序演算法java實現
阿新 • • 發佈:2018-11-25
package algorithm; /** * 氣泡排序演算法 * @author su * */ public class BubbleSort { public static void main(String[] args) { int[] a = {6,2,5,4,7,1,3,9,8}; //bubbleSort(a, a.length); bubbleSort2(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } /** * 氣泡排序的單趟排序過程 * @param a 陣列a * @param n 陣列的長度n */ private static void bubble(int[] a, int n){ for (int i = 0; i < n-1; i++) { if(a[i] > a[i+1]){ int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } private static void bubbleSort(int[] a, int n){ for (int i = n; i>=1; i--) { bubble(a, i); } } private static void bubbleSort2(int[] a){ for(int i = 1; i < a.length; i++){ for(int j = 0; j < a.length - i; j++){ if(a[j] > a[j+1]){ int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } }