8Jul/100
Subset Sum with a negative number
Problem:
Given a sorted array say int num[10]={-5,1,6,7,9,9,20,25,31,45}, write a function void findsum(int [],int x) that can print out all possible pair of elements in array that can make a sum equal to x. For example if value of x is 26, then function should print {1,25}, {25,1}, {-5,31}, {31,-5}.
private static void findSumFunction() {
//The problem provided me with an already-sorted array
final int[] testData = new int[]{-5,1,6,7,9,9,20,25,31,45};
final int X = 26;
/*first task is to loop through original sorted array and find out where
* searching can stop. If x = 26, then searching can stop once you get
* to numbers > 26 EXCEPT for the fact that there are negative number(s)
* in the test data.
* So first, find out what the lowest number is. If it is negative, adding a
* simple calculation to the algorithm will handle it.
* find lowest number to see if there is a negative number, this is O(1)
*/
if (testData[0] < lowestNumber) {
lowestNumber = testData[0];
}
System.out.println("lowestNumber is " + lowestNumber);
//1st go through array backward & stop before any value + negative num > X
//because those elem(s) are not needed. Worst case, this is O(n)
int rightIndex = testData.length - 1;
while (testData[rightIndex] + lowestNumber > X) {
int answer = testData[rightIndex] + lowestNumber;
System.out.println("don't need " + answer);
rightIndex--;
}
//Now go through the array frontward.Never go past rightIndex
//Simultaneously I am going through the array frontward and backward
int leftIndex = 0;
while (leftIndex < rightIndex) {
if (testData[leftIndex] + testData[rightIndex] == X) {
System.out.println(testData[leftIndex] + " + " + testData[rightIndex]);
leftIndex++;
rightIndex--;
}
else if (testData[leftIndex] + testData[rightIndex] < X) {
leftIndex++;
}
else {
rightIndex--;
}
}
}