Tuesday 2 January 2018

Program to find a pair with a given sum in an unsorted array


public class GFG1 {
public static void main(String[] args) {
// unsorted array
int[] arr = { 12, 16, 17, 18, 20, 21, 24, 28, 29, 37 };
// sum to be searched
int sum = 20;
int result = -1;
result = addsum(arr, sum);
if (result > -1)
System.out.println("found");
else
System.out.println("Not found");
}

public static int addsum(int[] arr, int sum) {
int start = 0;
int end = arr.length - 1;

while (start < end) {
System.out.println((arr[start] + arr[end]));
if ((arr[start] + arr[end]) == sum)
return 1;

if ((arr[start] + arr[end]) > sum)
end--;
else
start++;
}
return -1;
}
}