Skip to content

Instantly share code, notes, and snippets.

@tgvdinesh
Created November 18, 2016 08:29
Show Gist options
  • Save tgvdinesh/7d6cec6a5c3bd865ed7c458d7631d091 to your computer and use it in GitHub Desktop.
Save tgvdinesh/7d6cec6a5c3bd865ed7c458d7631d091 to your computer and use it in GitHub Desktop.
Divide and conquer approach to find if sum of any two value a and b is equal to user given input.
public class App {
public static void main(String[] args) {
int x = 8;
int[] arr = {-3, -2, 1, 7, 8, 11, 12, 21};
for (int i = 0; i < arr.length; i++) {
int a = arr[i];
int b = x - a;
if (b <= arr[arr.length - 1]) {
int result = divideAndConquer(arr, b, i + 1, arr.length - 1);
if (result != -1) {
System.out.println("Pair is (a + b) (" + a + " + " + b + ") x = " + x);
break;
}
}
}
}
private static int divideAndConquer(int[] values, int target, int start, int end) {
if (start > end) { // Code here means the value does not exist
return -1;
}
int middle = (start + end) / 2;
int value = values[middle];
if (value > target) {
return divideAndConquer(values, target, start, middle - 1);
}
if (value < target) {
return divideAndConquer(values, target, middle + 1, end);
}
return middle;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment