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

Answer

procedure binarysort$(a_1, a_2, a_3, ... a_n:$ A list of integers required to be sorted $)$ for $i:=2$ to $n$ $\space\space\space$index:= binarysearchmodif$(a_i$ ;$ a_1, a_2, a_3,...a_{i-1})$ {This would return the index of the first element which is greater than $a_i$} $\space\space\space$if index is not equal to $i$ $\space\space\space$$\space\space\space$store$:=a_i$ $\space\space\space$$\space\space\space$for $j:=$ index to $i$ $\space\space\space$$\space\space\space$$\space\space\space$$a_{j-1} := a_{j}$ $\space\space\space a_{index} := $ store procedure binarysearchmodif $(x:$ integer,$ a_1, a_2, . . . , a_n: $increasing integers$)$ $i := 1$ {i is left endpoint of search interval} $j := n $ {j is right endpoint of search interval} while $i < j$ $\space\space\space m := \left\lfloor \frac{(i + j)}{2}\right\rfloor$ $\space\space\space $if $x > a_m$ then $i := m + 1$ $\space\space\space $else $j := m$ if $a_i\le x$ then return $i+1$ else return $i$

Work Step by Step

This algorithm attempts to implement a sorting algorithm based on the binary search algorithm. First we modify the binary search algorithm so it returns the index of the first element greater than some $a_i$ for the $i^{th}$ iteration. When doing this, we reach a point where we have one element. Depending on the original set of values, this element could either be less than, greater than, or the same as our target. We handle each case and return an appropriate index. Since the left hand side of the set is sorted, that would be the location to where we should shift $a_i$ in the sort algorithm. Note that we do not simply swap since the left hand side would no longer be sorted then. We have to maintain that from iteration to another.
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.