(a) Describe the change that would have to be made to the bubble sort algorithm A so that the Numbers array is sorted into descending order. (b)(i) Explain why the second bubble sort algorithm B is more efficient than algorithm A.
Points that gain marks
- (a) Change > to < in the comparison: IF Numbers[Index] < Numbers[Index + 1] THEN.
- (b) In B the inner loop runs one time fewer on each pass of the outer loop …
- … because after each pass one more element at the end of the array is in its correct place.
- B's outer loop stops when a pass makes no swaps: the array is already sorted …
- … so fewer passes are needed.
In this lab: 'Stop early' runs the NoSwaps flag; 'The worst case' counts 4 + 3 + 2 + 1 comparisons as each pass gets shorter.