Bubble sort

Put the numbers in order from largest to smallest. You could use this to make a scoreboard with the highest score at the top.

It moves from left to right, comparing each pair of neighbors. If the number on the right is larger, the two swap places. For example, with 4 on the left and 8 on the right, the swap puts 8 on the left and 4 on the right.

One trip from the left end to the right end is called a pass. Each new pass starts on the left again. For two or more numbers, the algorithm makes one fewer pass than there are numbers. Six numbers take five passes.

Six numbers have five neighboring pairs. Five passes give us 5 × 5 = 25 comparisons. Let n be the number of items in a nonempty list. The algorithm compares n − 1 pairs on each of its n − 1 passes. That makes (n − 1)² comparisons, just under n² for a large list.

This is called quadratic growth. We write the algorithm’s time complexity as O(n²). When the list is already large, doubling the number of items means about four times as many comparisons.