A simple but not very efficient algorithm for arranging a set of n numbers in order of increasing magnitude. The method starts with the right-hand pair of numbers, swapping if necessary so that the smaller number is on the left of the pair, and proceeds towards the left, making a total of (n−1) comparisons. At the end of this pass the smallest number is at the left end of the line. The algorithm recommences with the right-hand pair of numbers and again proceeds towards the left. This time (n−2) comparisons are made and the pass ends with the second-smallest number in second position. The procedure is repeated until the complete ordering is achieved: this requires a total of n(n−1) comparisons.
16 | | 8 | | 13 | | 4 |
| | | | | × | |
16 | | 8 | | 4 | | 13 |
| | | × | | | |
16 | | 4 | | 8 | | 13 |
| × | | | | | |
4 | | 16 | | 8 | | 13 |
| | | | | ○ | |
4 | | 16 | | 8 | | 13 |
| | | × | | | |
4 | | 8 | | 16 | | 13 |
| | | | | × | |
4 | | 8 | | 13 | | 16 |
Bubble sort. Illustration of the simple neighbour-swapping algorithm. In the example × indicates a swap and ○ that no swap is required.