McGill University COMP251: Assignment 2 Solution
Question 1
The partition procedure on a sorted array of length
n
always gives an empty subarray
and an subarray of length
n
−
1. So in this case the running time
T
(
n
) of Quicksort satisFes:
T
(
n
) =
T
(
n
−
1) + Θ(
n
)
So we have
T
(
n
) =
T
(
n
−
1) + Θ(
n
)
=
T
(
n
−
2) + Θ(
n
−
1) + Θ(
n
)
=
T
(
n
−
3) + Θ(
n
−
2) + Θ(
n
−
1) + Θ(
n
)
. . .
=
T
(1) + Θ(2) + Θ(3) +
. . .
+ Θ(
n
−
1) + Θ(
n
)
= Θ(
n
2
)
As a result,
T
(
n
) = Ω(
n
2
).
Question 2
(a) ±or an array
A
that is sorted in increasing order, the pairs (
i, j
) satisfying the
given condition are
(1
,
2)
,
(1
,
3)
, . . . ,
(1
, n
)
,
(2
,
3)
,
(2
,
4)
, . . . ,
(2
, n
)
, . . . ,
(
n
−
1
, n
)
The number of such pairs is
(
n
−
1) + (
n
−
2) +
. . .
+ 1 =
(
n
−
1)
n
2
(b) The idea for a divideandconquer algorithm is as follows. Given a subarray
A
[
ℓ . . . r
], we
count the number of pairs (
i, j
) that satisfy the given condition (i.e.,
i < j
and
A
[
i
]
< A
[
j
]) by
dividing
A
[
ℓ . . . r
] into two halves
A
[
ℓ . . . m
] and
A
[(
m
+ 1)
. . . r
], and summing up the following
numbers:
1. the number of such pairs where
ℓ
≤
i < j
≤
m
, and
2. the number of such pairs where
m
+ 1
≤
i < j
≤
r
, and
3. the number of such pairs where
i
≤
m
and
m
+ 1
≤
j
The Frst two quantities are computed recursively, and we are looking for a way to compute the last
quantity in time
O
(
r
−
ℓ
), so that the total running time will satisfy
T
(
n
) = 2
T
(
n/
2) +
O
(
n
)
and the Master Theorem gives
T
(
n
) =
O
(
n
ln
n
).
(Note that a bruteforce way of computing the last quantity above–by comparing all number in
the Frst half with all number in the second half–requires (
r

ℓ
2
)
2
comparisons, so the running time
would satisfy
T
(
n
) = 2
T
(
n/
2) + Θ(
n
2
)
1