1.基本思想
冒泡排序的基本思想是,对相邻的元素进行两两比较,顺序相反则进行交换,这样,每一趟会将最小或最大的元素“浮”到顶端,最终达到完全有序
2.实现原理
冒泡排序是一种简单的排序算法,根据顺序两两相互比较的元素。如果是从大到小顺序,那么两个元素相互比较,大的会排在前面;反之,会排在后面。冒泡排序分为从大到小排序和从小到大排序。
3.代码实例
(1)代码:
public static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } System.out.print("第" + i + "趟: "); for (int num : arr) System.out.print(num + " "); System.out.println(); } }
public static void main(String[] args) { int[] array = {6, 2, 4, 1, 5, 9}; System.out.print("排序前: "); for (int num : array) System.out.print(num + " "); System.out.println(); bubbleSort(array); System.out.print("排序后: "); for (int num : array) System.out.print(num + " "); System.out.println(); }
(2)结果:
排序前: 6 2 4 1 5 9
第0趟: 1 6 4 2 5 9
第1趟: 1 2 6 4 5 9
第2趟: 1 2 4 6 5 9
第3趟: 1 2 4 5 6 9
第4趟: 1 2 4 5 6 9
第5趟: 1 2 4 5 6 9
排序后: 1 2 4 5 6 9
4.算法分析
根据上面这种冒泡实现,若原数组本身就是有序的(这是最好情况),仅需n-1次比较就可完成;若是倒序,比较次数为 n-1+n-2+...+1=n(n-1)/2,交换次数和比较次数等值。所以,其时间复杂度依然为O(n2),平均的空间复杂度为:O(1);