代码改变世界

冒泡排序

2012-07-29 13:39  coodoing  阅读(291)  评论(0编辑  收藏  举报

1、原理介绍

冒泡排序算法也是一种非常简单的排序算法,第一趟排序:n个数中,K1开始,依次比较两个相邻的关键字Ki和Ki+1(i=1,2,…,n-1),若Ki>Ki+1,则交换相应记录Ri和Ri+1的位置, 否则,不进行交换。经过这样一遍处理后,其中关键字最大的记录移到了第n个位置上。第二趟排序:对前面的n-1个记录进行第2遍排序,重复上述处理过程,第2遍之后,前n-1个记录中关键字最大的记录移到了第n-1个位置上,继续进行下去,直到不需要再交换记录为止。(最少比较次数为n-1是因为设置了change变量)

2.可视化演示

具体实现:

First Pass:
( 5 1 4 2 8 ) \to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) \to ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) \to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) \to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )

3、java代码实现

 1 public static int[] bubbleSort(int[] numbers) {
 2        
 3         // 冒泡排序算法:从左至右,大数后移。
 4         for(int i = numbers.length - 1; i > 0; i--) {
 5             for (int j = 0; j < i; j++) {
 6                 if (numbers[j] > numbers[j+1]) {
 7                     int temp = numbers[j];
 8                     numbers[j] = numbers[j+1];
 9                     numbers[j+1] = temp;
10                 }
11             }
12         }
13         return numbers;
14     }

4、复杂度分析

可以看出,冒泡排序的比较次数恒定,不受输入的影响,但具体的交换次数与输入有关。

复杂度

最佳情况下:O(n)

平均和最坏情况为:O(n^2)