For i=1..n-1
For j=n..i+1.
If a[j-1] and a[j] are out of order, swap.
| Original | 34 | 8 | 64 | 51 | 32 | 21 | Swaps |
| After i=1 | 4 | ||||||
| After i=2 | 8 | 3 | |||||
| After i=3 | 8 | 21 | 2 | ||||
| After i=4 | 8 | 21 | 32 | 34 | 51 | 64 | 0 |
| After i=5 | 8 | 21 | 32 | 34 | 51 | 64 | 0 |
What is bubbling?
What if the input data was already sorted in ascending order?
What if the input data was already sorted in descending order?
Is the sort stable?
How can you tell if the sorting is done early?
Bubble Sort: bubble [139]
% gcc -o bubble bubble.c > tcc bubble.c
Data File with Test Case: insert.dat: 6 34 8 64 51 32 21
% bubble insert.dat 6 27 15 [ 8 21 32 34 51 64 ] 0 0 % bubble insert.dat step n move comp 1 2 3 4 5 6 i j 6 0 0 [ 34 8 64 51 32 21 ] 0 0 6 3 1 [ 34 8 64 51 21 32 ] 1 6 6 6 2 [ 34 8 64 21 51 32 ] 1 5 6 9 3 [ 34 8 21 64 51 32 ] 1 4 6 9 4 [ 34 8 21 64 51 32 ] 1 3 6 12 5 [ 8 34 21 64 51 32 ] 1 2 6 15 6 [ 8 34 21 64 32 51 ] 2 6 6 18 7 [ 8 34 21 32 64 51 ] 2 5 6 18 8 [ 8 34 21 32 64 51 ] 2 4 6 21 9 [ 8 21 34 32 64 51 ] 2 3 6 24 10 [ 8 21 34 32 51 64 ] 3 6 6 24 11 [ 8 21 34 32 51 64 ] 3 5 6 27 12 [ 8 21 32 34 51 64 ] 3 4 6 27 13 [ 8 21 32 34 51 64 ] 4 6 6 27 14 [ 8 21 32 34 51 64 ] 4 5 6 27 15 [ 8 21 32 34 51 64 ] 5 6
Bubble Sort: bubble.c [140]
void bubble(input_type a[], int n) {
int i,j;
input_type tmp;
for (i=1; i<n; i++) /* Invariant: ? */
for (j=n; j>i; j--)
if (a[j] < a[j-1]) {
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
}
}
What is the invariant?
Bubble Sort: Analysis [141]
How many times does the outer loop execute?
How many times, on average, does the inner loop execute?
Data Compares: O( )
Data Moves: O( )
Exact Number of Data Compares:
Exact Number of Data Moves:
Sorting: Number of Moves [142]
What if input_type is a large record?
Then moves or swaps are expensive.
best-case worst-case avg-case
insertion
selection
bubble
In terms of moves, bubble and insertion are O( )
In terms of moves, selection is O( )
In terms of compares, all three algorithms are O( )