The times, to the nearest second, taken by 7 participants to answer a general knowledge question are 5, 7, 4, 9, 3, 5, 6.
The times are to be sorted into ascending order using the bubble sort algorithm.
a)
Write down
i)
the maximum number of passes the algorithm will require,
ii)
the number of comparisons required for the third pass,
iii)
the number of swaps there will be in the first pass.
i)
The maximum number of passes is
The maximum number of passes will be 6
ii)
The pass will have comparisons
The number of comparisons required in the third pass will be 4
iii)
Carefully do this by inspection (or you can carry out the first pass to be sure but that takes time)
The first swap will be the 7 and 4
The 9, being the highest value on the list, will then swap with each of the values that follow it (3 values)
The number of swaps in the first pass is 4
b)
After the second pass of the bubble sort algorithm, the times are in the order 4, 5, 3, 5, 6, 7, 9.
Perform the third pass of the bubble sort algorithm and state the number of swaps made.
As this is the third pass, the last two items on the list, 7 and 9, will already be in the correct place
The working list (that we apply a pass of the bubble sort algorithm to) will be 4, 5, 3, 5, 6
4 |
5 |
3 |
5 |
6 |
7 |
9 |
|
4 < 5, no swap |
4 |
5 |
3 |
5 |
6 |
7 |
9 |
|
5 > 3, swap |
4 |
3 |
5 |
5 |
6 |
7 |
9 |
|
5 = 5, no swap |
4 |
3 |
5 |
5 |
6 |
7 |
9 |
|
5 < 6, no swap |
4 |
3 |
5 |
5 |
6 |
7 |
9 |
|
end of pass 3 |
Number of swaps: 1
c)
Explain why two further passes of the bubble sort algorithm are required to ensure the list is in ascending order.
At this stage of the algorithm you should be able to deduce the answer by inspection of the current list
Using the answer to part (b), the current list is 4, 3, 5, 5, 6, 7, 9
The next pass will involve one swap - the 4 and the 3
The pass after that will involve no swaps and so the algorithm will be complete and the list will be in order
Thus, two further passes are required
It is important to state that the algorithm is complete and the reason why