Bubble Sort
Bubble Sort
1
8.3 Description
Suppose we have an array of data which is
unsorted:
Starting at the front, traverse the array, find the
largest item, and move (or bubble) it to the top
array[i] = max;
if ( sorted ) {
break;
}
}
}
Bubble sort
14
8.3.2.3 Range-limiting Bubble Sort
Intuitively, one may believe that limiting the loops
based on the location of the last swap may
significantly speed up the algorithm
For example, after the second pass,
we are certain all entries after 4 are
sorted
array[i] = max;
}
}
Bubble sort
16
8.3.2.3 Range-limiting Bubble Sort
Unfortunately, in practice, this does little to
affect the number of comparisons
Bubble sort
17
8.3.2.4 Alternating Bubble Sort
One operation which does significantly improve
the run time is to alternate between
bubbling the largest entry to the top, and
sinking the smallest entry to the bottom
while ( true ) {
int new_upper = lower;
upper = new_upper;
if ( lower == upper ) {
break;
}
lower = new_lower;
if ( lower == upper ) {
break;
}
}
}
Bubble sort
19
8.3.2.4 Run-time Analysis
Because the bubble sort simply swaps
adjacent entries, it cannot be any better than
insertion sort which does n + d comparisons
where d is the number of inversions