JIGYASA

An online placement forum.


You are not connected. Please login or register

@ Array Sum

Go down  Message [Page 1 of 1]

1 @ Array Sum on Tue Jun 22, 2010 3:56 am

Lucifer


Admin
A sorted array 'A' of 'N' positive nos. is given. Given a no. 'X', find if there are 2 nos. present in the given array such that there sum equals 'X'. ( looking for an efficient method )

View user profile http://jigyasa.forumn.org

2 Re: @ Array Sum on Fri Oct 14, 2011 2:10 pm

/*
A - array of positive nos.
N - no. of elements in the array
X - the search element
(no1, no2) - valid pair
*/

// returns if a valid pair is found. if yes, then (no1, no2) will hold that pair...
bool searchPair(int A[], int N, int X, int *no1, int *no2)
{
bool pairPresent = false;
int *p1 = A;
int *p2 = A + N - 1;
while ( p1 < p2 )
{
if ((*p1 + *p2) < X)
++p1;
else if ((*p1 + *p2) > X)
++p2;
else
{
*no1 = *p1;
*no2 = *p2;
pairPresent = true;
break;
}
}
return pairPresent;
}

Complexity - O(N)

View user profile

Back to top  Message [Page 1 of 1]

Permissions in this forum:
You cannot reply to topics in this forum