CSE 465
SOLUTIONS TO ASSIGNMENT 4
Spring 2008
This assignment is worth a total of 50 points.
1. [no points] Exercises 5.1.5 and 5.1.7 on page 163.
Exercise 5.1.5
In the pseudocode for insertion sort on page 161, the test condition in the
while
loop is
j
≥
0
and
A
[
j
]
>v
.
To eliminate the inbound condition
j
≥
0, we must be sure that the second part of the test condition stops
the loop when we go past the beginning of the data, so the sentinel value must fail the test of being greater
than
v
, i.e,, it must be less than or equal to
v
, which means that the sentinel must be at least as small as all
of the data.
(In pseudocode, one would simply write
∞
for this value. For the way to achieve this in C++, see the answer
to Problem 4 on the last assignment. In C++, one would also need to store the data starting at index 1, so
that index 0 could be used for the sentinel.)
Shortening the test this way just speeds up the code by a very small percentage; it does not change the eﬃciency
class.
Exercise 5.1.7
The version of insertion sort that uses swaps makes the same number of key comparisons, and its running time
will be in the same eﬃciency class in terms of Θnotation. However, it will be a bit slower because, even if the
swap procedure is coded inline, swap will still use two data transfers each time. (The original code only used
one each time, plus one at the beginning and one at the end. It also used fewer array accesses.)
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '08
 BURCHARDCHARLES

Click to edit the document details