java - Recursion: Determine if there are two elements in an array A that sum to k -
i've seen question asked lot. how works: check sum of first , last. if sum more k last-- or if less k first++. carries on recursively till either first == last or sum k found. **note values in array sorted in ascending order.
i've tried using recursion, whenever run it, returns "false". i've tried arrays of sizes , test cases return false. e.g. array[1 2 3 4 5 6], size n = 6 , k = 7 returns false when should true. cannot seem find bug. can please give me indication making mistake? , if i'm not mistaken runs in o(n) time?
public static boolean sum( int[] a, int n, int k ) //where k sum needed , n size of array { if (k <= a[0] || k >= a[n]*2) { return false; } int = 0; int j = n-1; return sum_recursion(a, n, k, i, j); } private static boolean sum_recursion(int[] a, int n, int k, int i, int j) { if(i == j) { return false; } else if((a[i] + a[j]) == k) { return true; } else if ((a[i] + a[j]) > k) { return sum_recursion(a, n, k, i, j--); } return sum_recursion(a, n, k, i++, j); }
two problems:
the j--, use j first, --. should j - 1 or --j. same story i++.
the n parameter seems useless. when use it, index out bounds.
fixed version correct result:
public static void main(string[] args) { int[] = {1, 2, 3, 4, 5, 6}; system.out.println(sum(a, 6, 7)); // ==> true } public static boolean sum(int[] a, int n, int k) //where k sum needed , n size of array { if (k <= a[0] || k >= a[n - 1] * 2) { return false; } int = 0; int j = n - 1; return sum_recursion(a, n, k, i, j); } private static boolean sum_recursion(int[] a, int n, int k, int i, int j) { if (i == j) { return false; } else if ((a[i] + a[j]) == k) { return true; } else if ((a[i] + a[j]) > k) { return sum_recursion(a, n, k, i, j - 1); } return sum_recursion(a, n, k, + 1, j); }
Comments
Post a Comment