/** * 原理: * 进行n次循环,每次循环从后往前对相邻两个元素进行比较,小的往前,大的往后 * * 时间复杂度: * 平均情况:O(n^2) * 最好情况:O(n) * 最坏情况:O(n^2) * * 稳定性:稳定 **/ public class 冒泡排序 { public int[] bubbleSort(int[] a, int n) { for (int i = 0; i < n; i++) { int flag = 0; for (int j = n - 1; j > i; j--) {// i or i-1 ? if (a[j] < a[j - 1]) { int x = a[j]; a[j] = a[j - 1]; a[j - 1] = x; flag = 1; } } if (flag == 0) break; } return a; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] a = new int[] { 25, 56, 32, 20, 1, 5, 89, 3, 8, 41 }; 冒泡排序 sort = new 冒泡排序(); sort.bubbleSort(a, a.length); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } }
For more articles related to java bubble sort algorithm code, please pay attention to the PHP Chinese website!