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

Answer

The number of comparisons is $\frac{n(n+1)-2}{2}$

Work Step by Step

Looking at the insertion sort algorithm, we can deduce a few things: We have $n-1$ loops and for each loop we do a certain number of comparisons. In our case, the values are arranged in ascending order. Looking at the inner loop, it is easy to note that for some loop iteration $i$, we have to compare $a_i$ against all the values before it until we reach $a_i$ again; hence, we have $i$ comparisons. We can sum those deductions in one equation: Number of comparisons $:= \sum_{i=2}^n{i} = 2+3+... n = \left(\sum_{i=0}^{n}i\right) - 1.$ The standard result is (from chapter 2:) $\sum_{i=0}^ni=\frac{n(n+1)}{2}$ . Applying this to the formula above, we get the number of comparisons to be $\frac{n(n+1)}{2} - 1 = \frac{n(n+1)-2}{2}$
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.