冒泡算法
/** * 冒泡算法 */ public class BubbleSortDemo2 { public static void main(String[] args) { int[] arr = new int[]{88, 33, 66, 22, 77, 44, 99, 11}; System.out.println("排序之前:"+Arrays.toString(arr)); int[] ints = BubbleSortDemo2.bubbleSort(arr); System.out.println("排序之后:"+Arrays.toString(ints)); } public static int[] bubbleSort(int[] arr) { for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } }
结果:
排序之前:[88, 33, 66, 22, 77, 44, 99, 11]
排序之后:[11, 22, 33, 44, 66, 77, 88, 99]