Discrete Mathematics and Its Applications, Seventh Edition

Published by McGraw-Hill Education
ISBN 10: 0073383090
ISBN 13: 978-0-07338-309-5

Chapter 3 - Section 3.1 - Algorithms - Exercises - Page 203: 37

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
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.