Saturday, June 30, 2012

3SUM algorithm

Problem is:
Given an array of integers, find subset of 3 elements of the array such that sum of those three elements is zero.
Brute force:
1. Find all 3-element subsets in the set S.
2. For each subset, find some of each subset
3. Print the one whose sum is zero
Alternative and improved:
1. Sort the list.
2. Following is the algorithm

-25 -10 -7 -3 2 4 8 10  (a+b+c==-25)
 -25 -10 -7 -3 2 4 8 10  (a+b+c==-22)
 . . .
 -25 -10 -7 -3 2 4 8 10  (a+b+c==-7)
 -25 -10 -7 -3 2 4 8 10  (a+b+c==-7)
 -25 -10 -7 -3 2 4 8 10  (a+b+c==-3)
 -25 -10 -7 -3 2 4 8 10  (a+b+c==2)
 -25 -10 -7 -3 2 4 8 10  (a+b+c==0)


where bold one is 'a' and red ones are 'b' and 'c' - shown in the parenthesis on the right.

Following is the working code:

class tuple
{
private:
int i;
int j;
int k;
public:
tuple() { i = 0; j = 0; k = 0; }
tuple(int a, int b, int c) { i = a; j = b; k = c; }
int GetI() { return i; }
int GetJ() { return j; }
int GetK() { return k; }
void SetI(int a) { i = a; }
void SetJ(int b) { j = b; }
void SetK(int c) { k = c; }
};

int compare (const void* a, const void *b)
{
return (*(int*)a - *(int*)b);
}

tuple* SUM (int *a, int n)
{
if (a == NULL) return NULL;
if (n <= 2) return NULL;

qsort (a, n, sizeof(int), compare);
cout << "Sorting complete \n";
cout << "Sorted array is:\n";
for (int i = 0; i < n; i++)
cout << a[i] << '\t';

cout << endl;

for (int i = 0; i < n - 3; i++)
{
int j = i + 1;
int k = n - 1;
while (j < k)
{
if (a[i] + a[j] + a[k] == 0)
return new tuple(i, j, k);
if (a[i] + a[j] + a[k] < 0)
j++;

if (a[i] + a[j] + a[k] > 0)
k--;
}
}

return NULL;
}


No comments:

Post a Comment