As suggested by @leif in the comment, start from the begin and end of array
, move the begin index or end index if the sum is greater or smaller. you should find a begin and end index
such that their values equal sum
. if not, you there exists no such indices. something on this line below. I have not tested this code and assuming positive integers
The code below is self explanatory:
public static void sumSortedArray2(int[] arr, int sum){
boolean found=false;
int max=arr.length-1;
int min=0;
while (min<max){
if(arr[min]+arr[max]<sum)
min++;
else if (arr[min]+arr[max]>sum)
max--;
else {
found =true;
break;
}
}
if (found){
System.out.printf("The two indices are %s and %s%n ",min,max);
}
else {
System.out.printf("The sum:%s cannot be formed with given array:%s",sum,Arrays.toString(arr));
}
}