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

Answer

Check the solution for the steps by both algorithms

Work Step by Step

The list of the numbers is $\{3, 4,5, 6, 8, 9, 11\}$ a) The linear search would work as follows: It would begin by iterating over the list inspecting each element until it reaches the target. For the first element $a_1$ which is $3$, It compares it to the target $9$; finding that it's not what it's looking for, it continues its search. The same procedure happens for elements number $2,3,4$ and $5$. At the $6^{th}$ index, $a_6$ is the target and hence the search returns $6$. b) The binary search would work as follows. Notice that for each iteration, we have a left endpoint, a right endpoint and a mid-point. These will be referred to as left, right, and mid and will be modified after each cycle accordingly. left $:=1,$ right $:=7$, mid$:=\left \lfloor{\frac{1+7}{2}}\right \rfloor := 4$ We compare $9$ to $a_4\to9\gt6\to$ We limit our search to the right group, namely {${8, 9, 11}.$} We update left to mid $+ 1 := 5$. Now, our new set of indices are: left $:=5,$ right $:=7$, mid$:=\left \lfloor{\frac{5+7}{2}}\right \rfloor := 6$ We compare $9$ to $a_6$ and since $9\not\gt9$, we limit our search to the left subgroup of the set, namely ${8, 9}$. Notice that we have found the target (and in some variants of binary search, depending on the implementation, the algorithm would return this index; however, the book's implementation continues until only one element remains in the set and then returns it if it's valid or not). Our new set of indices are: left $:=5,$ right $:=6$, mid$:=\left \lfloor{\frac{5+6}{2}}\right \rfloor := 5$. We compare $9$ to $a_5$ and seeing as $9\gt8$. We limit our search to the right set, namely {$9$}. Seeing as we now have only one element in the set, binary search checks if it's equal to the target (which it is in this case) and returns its index $6$ .
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.