Wednesday, December 7, 2011

Introduction to Algorthms 3rd --P2.3.7

Describe aO(n *lg n)-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x.

This is the usual solution:
---------------------------------------------------------

Input: An array A and a value x.
Output: A boolean value indicating if there is two elements in A whose sum is x.
A ← SORT(A)
n ← length[A]
for i ← to n do
if A[i] 0 and B INARY-SEARCH(A, A[i] − x, 1, n) then
return true
end if
end for
return false
---------------------------------------------------------
My idea is to use merge sort.

x is sum of two numbers. then x/2 must be between those two numbers. in other words, if there are two numbers A and B whose sum is x, then A must be on the left of x and B must be on the right side of x.

The above idea cannot work. Because there is no way to determine how many elements should be chosen from left or right side of x/2.

No comments:

Post a Comment