In: Computer Science
Is there any way to do this function
//Recursive method to check if two numbers form a given
number
private static boolean addition(int[] array, int start, int end,
int n) {
if(start < end) {
if (array[start] + array[end] == n) {
return true;
}
if (array[start] + array[end] > n) {
return addition(array, start, end-1, n);
}
if (array[start] + array[end] < n) {
return addition(array, start+1, end, n);
}
}
return false;
}
Function corrected:
private static boolean addition(int[] array, int start, int end,
int n) {
Arrays.sort(array,start,end+1);
//sort the array
if(start < end)
{
if (array[start] + array[end] == n) {
return true;
}
if (array[start] + array[end] > n) {
return addition(array, start, end-1, n);
}
if (array[start] + array[end] < n) {
return addition(array, start+1, end, n);
}
}
return false;
}
whole program to test
// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;
class Solution {
// Function to check if array has 2 elements
// whose sum is equal to the given value
private static boolean addition(int[] array, int
start, int end, int n) {
Arrays.sort(array,start,end+1);
//sort the array
if(start < end)
{
if (array[start] + array[end] == n) {
return true;
}
if (array[start] + array[end] > n) {
return addition(array, start, end-1, n);
}
if (array[start] + array[end] < n) {
return addition(array, start+1, end, n);
}
}
return false;
}
// Driver code
public static void main(String args[])
{
Solution s = new Solution();
int A[] = { 1, 4, 45, 6, 10, -8
};
int n = 16;
int arr_size = A.length;
// Function calling
if (s.addition(A, 0,arr_size-1,
n))
System.out.println("Array has two "
+ "elements with given sum");
else
System.out.println("Array doesn't have "
+ "two elements with given sum");
}
}