JIGYASA
Would you like to react to this message? Create an account in a few clicks or log in to continue.
JIGYASA

An online placement forum.


You are not connected. Please login or register

@ Array Sum

2 posters

Go down  Message [Page 1 of 1]

1@ Array Sum Empty @ Array Sum 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 )

https://jigyasa.forumotion.com

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

codecrker



/*
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)

Back to top  Message [Page 1 of 1]

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