Bubble Sort

Bubble Sort
Bubble Sort: Algorithm

Assume that we use an array of integers A
with N elements.
for (p = 0; p < N; p++) // pass p
for (e = 1; e < N - p; e++) // sort sub-array A[0...(N-p)]
if (A[e-1] > A[e]) // sort in non-decreasing order
Swap(A[e-1], A[e]);
Bubble-Sort on a Sequence
Original data sequence:
572693
=================
527693
526793
526739
==End of Pass 1====
25673|9
25637|9
==End of Pass 2====
2536|79
==End of Pass 3====
235|679
==End of Pass 4====
Analysis: Best Case and Worst Case

If the given list is ordered in reverse order, we do:
–
–

If the given list is ordered in “random” order, we do:
–
–

N(N-1) comparisons
less than N(N-1) swaps
If the given list is already sorted, we do:
–
–

N(N-1) comparisons (if statement)
N(N-1) swaps (function Swap())
N(N-1) comparisons
no swaps
In all 3 cases, the running time is O(N2) due to N(N-1)
comparisons.
Optimizing the Bubble Sort
The previous algorithm can be optimized, if the
program stops as soon as it is detected that no
swap has been made during a pass. In this
case, a Boolean variable swapped can be
used, that is set to FALSE at the beginning of
every pass. swapped will then be set to TRUE
whenever a swap is made. At the end of a
pass, if swapped still keeps the value FALSE,
the program stops.
Optimizing the Bubble Sort
swapped = TRUE;
for (p = 0; p < N && swapped; p++)
{
swapped = FALSE;
for (e = 1; e < N - p; e++)
// pass p
// sort sub-array A[0...(N-p)]
if (A[e-1] > A[e])
{
swap(A[e-1], A[e]);
swapped = TRUE;
}
}
If the given list is already sorted,
only (N-1) comparisons need to
be done before the program
stops. So the best-case running
time of the optimized Bubble Sort
is W(N).