Answer
Check below for the solution.
Work Step by Step
To modify the bubble sort, we add a boolean variable that tells us if any changes occurred during that iteration of the algorithm. If and only if no changes were done, then the algorithm should terminate.
Reproduced below is the bubble sort algorithm from the chapter below with the added lines underlined:
procedure bubblesort(a1, . . . , an : real numbers with n ≥ 2)
for i := 1 to n − 1
$\space\space\space \rm \underline{change := false}$
$\space\space\space$for j := 1 to n − i
$\space\space\space\space\space\space$if aj > aj+1
$\space\space\space\space\space\space\space\space$interchange aj and aj+1
$\space\space\space\space\space\space\space\space \rm \underline{change :=true}$
$\space\space\space \rm \underline {if \space change\space is\space not \space true\space then \space terminate\space sort} $
{a1, . . . , an is in increasing order}
Notice that change would be changed to true if and only if we do a swap. If after the end of the inner loop, change is still false, then the algorithm should terminate