This preview shows pages 1–2. Sign up to view the full content.
CS3230
Tutorial 3
Q2. Given an array
A
of integers and a number
k
, give an eﬃcient algorithm to decide if
there exist two elements
A
[
i
] and
A
[
j
],
i
6
=
j
, such that
A
[
i
] +
A
[
j
] =
k
. Give time complexity
bound of your algorithm.
Ans: (A) Sort the array (takes
O
(
n
log
n
) time).
(B) For each
j
, use binary search to check if the array contains the element
k

A
[
j
] (as
A
[
i
], with
i
6
=
j
).
Time complexity:
O
(
n
log
n
) for step (A) above.
O
(log
n
) for each
j
in step (B), and thus
O
(
n
log
n
) for step (B).
Alternatively, a better way to do step (B) is as follows:
Suppose array
A
[1 :
n
] is sorted.
i
= 1;
j
=
n
.
While
i < j
do
{
If
A
[
i
] +
A
[
j
] =
k
, then output yes.
Else If
A
[
i
] +
A
[
j
]
< k
, then
i
=
i
+ 1.
Else If
A
[
i
] +
A
[
j
]
> k
, then
j
=
j

1.
}
The above will do step (B) in
O
(
n
) time. However, the overall complexity of steps (A) and
(B) still remains
O
(
n
log
n
).
Q3. Consider the following modiﬁcation of the partition algorithm done in class. Show that
it works correctly.
Partition(
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 '10
 sanjay
 Algorithms, Sort

Click to edit the document details