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 202: 15

Answer

procedure insert ($x:$ integer to be inserted, $a_1, a_2, ..., a_n:$ list of integers arranged in increasing order) for $i:=1$ to $n$ $\space\space\space$ if $x

Work Step by Step

The algorithm attempts to locate the position at which to insert the element $x$ in the arranged set. Two main points have to be made: First, notice that when iterating though the loop, we check if the current element is strictly greater than $x.$ As soon as that is true, we insert $x$ before that element. This is because we know that up to that point, not a single element we met was strictly greater than $x$ and hence all were either less than or equal. Hence, placing $x$ will retain the order of the integers. The second line is necessary for the edge case when $x$ is greater than all the elements of the set. If you trace the loop, you would notice that $x$ is never inserted into the set when it is greater than every element. This is why we have to explicitly add the final line.
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.