Returns the number of pairs in the array and N.
/*
Find the pair in an array... that sum up to particle number
Company: Linkedin
Date: 8/11/2011
*/
# Include <iostream>
# Include <cstdlib>
# Include <ctime>
Int randomPartition (int A [], int low, int high );
Void quickSort (int A [], int low, int high );
Bool findPair (int A [], int size, int sum, std: pair <int, int> & result );
Void quickSort (int A [], int low, int high)
{
If (low> = high)
Return;
Int partition = randomPartition (A, low, high );
QuickSort (A, low, skip-1 );
QuickSort (A, latency + 1, high );
}
Int randomPartition (int A [], int low, int high)
{
Srand (time (int) 0 ));
Int index = low + rand () % (high-low + 1 );
Int t = A [high];
A [high] = A [index];
A [index] = t;
Int key = A [high];
Int I = low-1;
For (int j = low; j {
If (A [j] <= key)
{
I ++;
Int t = A [I];
A [I] = A [j];
A [j] = t;
}
}
I ++;
T = A [high];
A [high] = A [I];
A [I] = t;
Return I;
}
Bool findPair (int A [], int size, int sum, std: pair <int, int> & result)
{
QuickSort (A, 0, size-1 );
Int I = 0;
Int j = size-1;
While (I <j)
{
If (A [I] + A [j] = sum)
{
Result. first = A [I];
Result. second = A [j];
Return true;
}
Else if (A [I] + A [j] <sum)
I ++;
Else
J --;
}
Return false;
}
Void main ()
{
Int A [10] = {-2,-5, 1, 4, 3, 9, 6, 5, 7, 0 };
Int sum;
Std: cout <"Please enter a sum value \ n ";
Std: cin> sum;
Std: pair <int, int> result (0, 0 );
If (findPair (A, 10, sum, result ))
Std: cout <result. first <"+" <result. second <"=" <sum <"\ n ";
Else
Std: cout <"No pair found \ n ";
}
This article is from the "interview" blog