Knowledge Base > Algorithms & Data Structures > Sorting Algorithms

Bubble Sort

Algorithm Analysis
The bubble sort is the oldest and simplest sort in use. Unfortunately, it's also the slowest.

The bubble sort works by comparing each item in the list with the item next to it, and swapping them if required. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items (in other words, all items are in the correct order). This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.

The bubble sort is generally considered to be the most inefficient sorting algorithm in common usage. Under best-case conditions (the list is already sorted), the bubble sort can approach a constant O(n) level of complexity. General-case is an abysmal O(n2).

While the insertion, selection, and shell sorts also have O(n2) complexities, they are significantly more efficient than the bubble sort.

Pros: Simplicity and ease of implementation.
Cons: Horribly inefficient.

Empirical Analysis

Bubble Sort Efficiency
Bubble Sort Efficiency Graph

The graph clearly shows the n2 nature of the bubble sort.

A fair number of algorithm purists (which means they've probably never written software for a living) claim that the bubble sort should never be used for any reason. Realistically, there isn't a noticeable performance difference between the various sorts for 100 items or less, and the simplicity of the bubble sort makes it attractive. The bubble sort shouldn't be used for repetitive sorts or sorts of more than a couple hundred items.

Source Code
Below is the basic bubble sort algorithm.

void bubbleSort(int numbers[], int array_size)
  int i, j, temp;

  for (i = (array_size - 1); i >= 0; i--)
    for (j = 1; j <= i; j++)
      if (numbers[j-1] > numbers[j])
        temp = numbers[j-1];
        numbers[j-1] = numbers[j];
        numbers[j] = temp;

A sample C program that demonstrates the use of the bubble sort may be downloaded here.

Michael's Homepage      WKU-Linux