Penguin
Annotated edit history of BubbleSort version 4, including all changes. View license author blame.
Rev Author # Line
4 AristotlePagaltzis 1 [BubbleSort] is the cannonical example of an inefficient sorting [Algorithm]. It works by moving through the array comparing each element with the next element and swapping them if they're in the wrong order. In each iteration, it moves the next largest element into the next last position, stopping one position earlier than previously. An example:
1 StuartYeates 2
2 AristotlePagaltzis 3 ||After Iteration||||Element Nr.
4 |Outer|Inner|0|1|2|3
5 ||^Initial state | D | B | C | A
6 | 1 | 1 | [[B] | [[D] | C | A
7 | 1 | 2 | B | [[C] | [[D] | A
8 | 1 | 3 | B | C | [[A] | [[__D__]
9 | 2 | 1 | [[B] | [[C] | A | D
10 | 2 | 2 | B | [[A] | [[__C__] | D
11 | 3 | 1 | [[A] | [[__B__] | C | D
1 StuartYeates 12
2 AristotlePagaltzis 13 The brackets denote the elements which were compared (and possibly swapped) during an iteration. Bold elements have reached their final position. As you can see, the next largest element falls into the next last position after each iteration.
14
3 AristotlePagaltzis 15 A sample implementation might be
1 StuartYeates 16
17 int [] array;
2 AristotlePagaltzis 18 for(int i = array.length - 2 ; ; i--) {
19 for(int j = 0; j < i ; i++)
20 if (array[[j]>array[[j+1])
21 swap(array[[j], array[[j+1]);
1 StuartYeates 22 }
23
2 AristotlePagaltzis 24 It is obvious that, with ''n'' being the array's length, the inner loop will total ''(n / 2) * (n - 1)'' iterations - which is ''(n^2 - n) / 2''. Therefor, in [BigONotation], the complexity of BubbleSort is ''O(n^2)''. Clearly, its performance will degrade quickly as the array grows.
25
26 BubbleSort does have some good features, though:
27 # The weakness of BubbleSort is that it never shuffles non-adjacent elements - that's why it's so slow. But it also means that never degrades the order in its input, so you can take shortcuts if you know your list is nearly sorted. F.ex, if ''a'' unsorted elements have been prefixed to an otherwise sorted list then the outer loop can be aborted early, reducing the complexity to ''O(a n)''. For small values of ''a'', this will likely be less than the ''O(n log n)'' required f.ex by a full QuickSort run.
28 # [BubbleSort] can use fine-grained [Synchronisation] to sort a list while other threads or processes are updating it or changing it.