Task: A and B are arrays of natural numbers. A is an incrementally sorted array and B is randomly ordered one. K is some arbitrary natural number. Find an effective algorithm which determines all possible pairs of indexes (i,j) such that A[i]+B[j]=K.
Is this algorithm the most efficient?
public static void main(String[] args) {
int A[] = { 1, 2, 3, 4, 6, 7, 8, 11, 13, 124};
int B[] = {4, 1, 10, 5};
int k = 10;
int i = 0, n = A.length, m = B.length;
ArrayList<String> result = new ArrayList<String>();
while (i < n){
if (A[i] >= k) {
break;
}else {
int j = 0;
while(j < m) {
if (A[i] + B[j] == k) {
result.add("i = " + i + " j = " + j);
}
j++;
}
}
i++;
}
for(int z = 0; z < result.size(); z++) {
System.out.println(result.get(z));
}
}
Aare distinct?