How quick is bubble sort?

Share this page

We said in the main article that in the worst case bubble sort will need $n(n-1)2$ steps to sort a list of $n$ things. Here's a proof.

Let's assume that the things we are sorting are numbers and that they need to be put in ascending order. On the first run through the list the algorithm has to compare the first and second number, then the second and third, then the third and fourth, and so on. For $n$ numbers that's a total of $n-1$ comparisons (and potential swaps).

Since we are looking at the worst case scenario we have to assume the list is not yet sorted, so a second iteration is needed. However, the first iteration will have made sure that the largest number in your list, call it $x$, will have moved to the end of the list. That’s because the comparison involving $x$ and the number that comes after it will have resulted in a swap moving $x$ one place to the right (since $x$ is largest of the list and therefore also larger than its right-hand neighbour). The next comparison will then also involve $x$ together with its new right-hand neighbour, and also result in a swap moving $x$ one place to the right. Continuing like this, you see that $x$ eventually moves to the end of the list in one iteration. (If the largest number $x$ appears several times in the list, then this argument works a little differently, but the result is still the same: the last number in the list after the first iteration will be $x$.)

The fact that the largest number $x$ is in its correct place (at the end of the list) means that on the second iteration of the algorithm we can ignore this last number. This means that on the second iteration the algorithm has to compare consecutive numbers in a list of $n-1$ numbers, giving a total of $n-2$ comparisons (and potential swaps) for the second iteration.

Since we are looking at the worst case scenario we have to assume the list is not yet sorted, so a third iteration is needed. By the same reasoning as in the previous paragraphs, on the third iteration the algorithm will need to make $n-3$ comparisons (and potential swaps).

Carrying on like this, we see that in the worst case scenario the algorithm will need a total of

  \[ (n-1)+(n-2)+(n-3)+...+1 \]    

steps.

From the formula for the summation of integers (see here) we know that

  \[ (n-1)+(n-2)+(n-3)+...+1 = n(n-1)/2. \]    
This proves the result.

Back to the main article