Let us arrange the following list of eight numbers in ascending order, i.e., from the smallest to the largest.
52 | 12 | 17 | 49 | 73 | 24 | 92 | 62 |
In the form of an algorithm, this method becomes:
In the first run, we find the smallest item from the given list of numbers, which is 12 and it is swapped with Item K (K = 1). So, the list at the end of the first run through the algorithm looks like:
12 | 52 | 17 | 49 | 73 | 24 | 92 | 62 |
12 | 17 | 52 | 49 | 73 | 24 | 92 | 62 |
12 | 17 | 24 | 49 | 73 | 52 | 92 | 62 |
12 | 17 | 24 | 49 | 73 | 52 | 92 | 62 |
12 | 17 | 24 | 49 | 52 | 73 | 92 | 62 |
12 | 17 | 24 | 49 | 52 | 62 | 92 | 73 |
12 | 17 | 24 | 49 | 52 | 62 | 73 | 92 |
If you notice carefully, there are two repeat statements. The first one runs N-1 times. The second also seems to run for N-1 times but with a difference: it is also influenced by K. See if you can convince yourselves that the second repeat runs from K to the end of the list each time.
Therefore, the second loop does N-1 comparisons the first time, N-2 comparisons the second time, N-3, the third time, N-4, the fourth time and all the way down to 1 comparison the last (or the N-1) time.
The total number of comparisons is thus \[ N-1 + N-2 + N-3 + \ldots + 1 = \frac{(N-1)(N)}{2} \] For our problem, N = 8 and the number of comparisons is \[(8-1)(8)/2 = (7\times8)/2 = \fbox{28}\]
In this method, we compare every item with its next item. If the second item is smaller, we swap the two and continue until no more swaps are possible. At this point, the items in the list must be in ascending order.
Its name comes from the fact that the largest item bubbles through to the end of the list each time we run through the list. It is obvious then that we need to run through the list N-1 times.
Again, here is the input list.
52 | 12 | 17 | 49 | 73 | 24 | 92 | 62 |
At the end of the first round of repeat for loop, we have the following list.
12 | 17 | 49 | 52 | 24 | 73 | 62 | 92 |
In the second round, we compare pairs of items starting from the first item to N-2 item (remember that K = 2). The list at the end of second round is
12 | 17 | 49 | 24 | 52 | 62 | 73 | 92 |
By the end of the third round, every item is in correct position and ...
12 | 17 | 24 | 49 | 52 | 62 | 73 | 92 |
... there are no more swaps in the fourth round. The list is in ascending order.
There are two repeat statements in this algorithm too. The first one runs N-1 times. The second repeat runs from 1 to N-K each time.
Therefore, the second loop does N-1 comparisons the first time, N-2 comparisons the second time, N-3, the third time, N-4, the fourth time and all the way down to 1 comparison the last (or the N-1) time.
The total number of comparisons is thus \[ N-1 + N-2 + N-3 + \ldots + 1 = \frac{(N-1)(N-2)}{2} \] In our particular instance of the problem, it took only 4 rounds of comparisons, that is \[ (8-1) + (8-2) + (8-3) + (8-4) = \fbox{22}\]