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: 21

Answer

procedure arrange $( a_1, a_2, a_3, ...: $ a sequence of integers $)$ if $(a_2>a_3)$ then swap $(a_2, a_3)$ if $ (a_1 > a_2)$ then swap $(a_1, a_2)$ if $(a_2 > a_3)$ then swap $(a_2, a_3)$ procedure swap $(a_1, a_2)$ {swaps the values of two variables} temp $:= a_1$ $a_1 := a_2$ $a_2:= $temp

Work Step by Step

This algorithm attempts to arrange the first three values of a sequence. Notice that we first define a smaller algorithm called swap to avoid having to repeat the same code three times. Notice also that we compared $a_2$ and $a_3$ twice. This makes more sense when you consider the following sequence $10, 2, 3, ...$. In this case, $a_1$ is the largest value and it would need two steps for it to reach $a_3$. It first moves from $a_1$ to $a_2$ but then we need another statement to make sure it moves to $a_3.$
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.