ECE368 Homework #1
1. (20 points)
Consider the following procedure acting on an array
A
[
1
..
n
]
.
INSERTION
SORT(
A
[
1
..
n
]
)
Cost
Times
1.
for
j
←
2
to
n
C
1
n
2.
key
←
A
[
j
]
C
2
n

1
3.
i
←
j

1
C
3
n

1
4.
while
i
>
0
and
A
[
i
]
>
key
C
4
∑
n
j
=
2
t
j
5.
A
[
i
+
1
]
←
A
[
i
]
C
5
∑
n
j
=
2
(
t
j

1
)
6.
i
←
i

1
C
6
∑
n
j
=
2
(
t
j

1
)
7.
A
[
i
+
1
]
←
key
C
7
n

1
(a) Let
t
j
denote the number of times the while loop test in line 4 is executed for that value of
j
.
Fill in for each line of instruction, the number of times the instruction is executed.
(b) Derive the expression for the running time of
INSERTION
SORT
in terms of
n
,
C
i
, and
t
j
.
Let
T
(
n
) =
running time of
INSERTION
SORT
.
T
(
n
) =
C
1
n
+
C
2
(
n

1
)+
C
3
(
n

1
)+
C
4
n
∑
j
=
2
t
j
+
C
5
n
∑
j
=
2
(
t
j

1
)+
C
6
n
∑
j
=
2
(
t
j

1
)+
C
7
(
n

1
)
(c) What is
t
j
for the bestcase scenario, i.e., when the running time of the algorithm is the smallest.
Use that to derive the expression for the bestcase running time of
INSERTION
SORT
in terms of
n
and
C
i
. What is the bestcase time complexity of
INSERTION
SORT
using the bigO notation?
The array is already sorted. All
t
j
are 1. Therefore,
T
(
n
) =
C
1
n
+
C
2
(
n

1
)+
C
3
(
n

1
)+
C
4
(
n

1
)+
C
7
(
n

1
)
= (
C
1
+
C
2
+
C
3
+
C
4
+
C
7
)
n

(
C
2
+
C
3
+
C
4
+
C
7
)
.
T
(
n
) =
O
(
n
)
. (In fact,
T
(
n
) =
Θ
(
n
)
.)
(d) What is
t
j
for the worstcase scenario, i.e., when the running time of the algorithm is the largest.
Use that to derive the expression for the worstcase running time of
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.
 Fall '08
 Staff
 Insertion Sort, Big O notation, running time

Click to edit the document details