This fle contains the exercises, hints, and solutions For Chapter 7 oF the
book ”Introduction to the Design and Analysis oF Algorithms,” 2nd edition, by
A. Levitin. The problems that might be challenging For at least some students
are marked by
±
;
those that might be diﬃcult For a majority oF students are
marked by
²
.
Exercises 7.1
1. Is it possible to exchange numeric values oF two variables, say,
u
and
v
,
without using any extra storage?
2. Will the comparison counting algorithm work correctly For arrays with
equal values?
3. Assuming that the set oF possible list values is {
a, b, c, d
}, sort the
Following list in alphabetical order by the distribution counting algorithm:
b, c, d, c, b, a, a, b.
4. Is the distribution counting algorithm stable?
5. Design a one-line algorithm For sorting any array oF size
n
whose values
are
n
distinct integers From 1 to
n.
6.
±
The
ancestry problem
asks to determine whether a vertex
u
is an
ancestor oF vertex
v
in a given binary (or, more generally, rooted ordered)
tree oF
n
vertices.
Design a
O
(
n
)
input enhancement algorithm that
provides suﬃcient inFormation to solve this problem For any pair oF the
tree’s vertices in constant time.
7.
²
The Following technique, known as
virtual initialization
, provides a
time-eﬃcient way to initialize just some elements oF a given array
A
[0
..n
−
1]
so that For each oF its elements, we can say in constant time whether it
has been initialized and, iF it has been, with which value.
This is done
by utilizing a variable
counter
For the number oF initialized elements in
A
and two auxiliary arrays oF the same size, say
B
[0
..n
−
1]
and
C
[0
..n
−
1]
,
defned as Follows.
B
[0]
,...,B
[
counter
−
1]
contain the indices oF the el-
ements oF
A
that were initialized:
B
[0]
contains the index oF the element
initialized frst,
B
[1]
contains the index oF the element initialized second,
and so on. ±urthermore, iF
A
[
i
]
was the
k
th element
(0
≤
k
≤
counter
−
1)
to be initialized,
C
[
i
]
contains
k.
a. Sketch the state oF arrays
A
[0
..
7]
,B
[0
..
7]
,
and
C
[0
..
7]
aFter the three
assignments
A
[3]
←
x
;
A
[7]
←
z
;
A
[1]
←
y.
b. In general, how can we check with this scheme whether
A
[
i
]
has been
initialized and, iF it has been, with which value?
1