You are on page 1of 6

Bubble Sort

Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in
a blue moon and its main application is to make an introduction to the sorting
algorithms. Bubble sort belongs to O(n
2
) sorting algorithms, which makes it quite
inefficient for sorting large data olumes. Bubble sort is stable and adaptive.
Algorithm
!. "ompare each pair of ad#acent elements from the beginning of an arra$ and, if
the$ are in reersed order, swap them.
2. If at least one swap has been done, repeat step !.
%ou can imagine that on eer$ step big bubbles float to the surface and sta$ there. &t
the step, when no bubble moes, sorting stops. 'et us see an e(ample of sorting an
arra$ to make the idea of bubble sort clearer.
Example. )ort *+, !, !2, -+, !,- using bubble sort.
Complexity analysis
&erage and worst case comple(it$ of bubble sort is O(n
2
). &lso, it makes O(n
2
) swaps
in the worst case. Bubble sort is adaptie. It means that for almost sorted arra$ it gies
O(n) estimation. &oid implementations, which don.t check if the arra$ is alread$
sorted on eer$ step (an$ swaps made). /his check is necessar$, in order to presere
adaptie propert$.
Turtles and rabbits
One more problem of bubble sort is that its running time badl$ depends on the initial
order of the elements. Big elements (rabbits) go up fast, while small ones (turtles) go
down er$ slow. /his problem is soled in the "ocktail sort.
Turtle example. /hought, arra$ *2, 0, 1, +, !- is almost sorted, it takes O(n
2
) iterations
to sort an arra$. 2lement *!- is a turtle.
Rabbit example. &rra$ *,, !, 2, 0, 1, +- is almost sorted too, but it takes O(n)
iterations to sort it. 2lement *,- is a rabbit. /his e(ample demonstrates adaptie
propert$ of the bubble sort.
Code snippets
/here are seeral wa$s to implement the bubble sort. 3otice, that 4swaps4 check is
absolutel$ necessar$, in order to presere adaptie propert$.
Java
public void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < arr.length j; i++)
{
if (arr[i] ! arr[i + "]) {
tmp = arr[i];
arr[i] = arr[i + "];
arr[i + "] = tmp;
swapped = true;
#
#
#
#
C++
$oid bubbleSort(int arr[]% int n) {
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = &alse;
j++;
&or (int i = 0; i < n j; i++) {
i& (arr[i] ! arr[i + "]) {
tmp = arr[i];
arr[i] = arr[i + "];
arr[i + "] = tmp;
swapped = true;
#
#
#
#

You might also like