I have an array A
of integers with n values and an integer x
. I need to find all the pairs in that array whose absolute difference is equal to x
.
For example, take A = {13, 1,-8, 21, 0, 9,-54, 17, 31, 81,-46}
and x = 8
, my algorithm should print this:
0 & 3 with values 13 & 21
1 & 5 with values 1 & 9
2 & 4 with values -8 & 0
5 & 7 with values 9 & 17
6 & 10 with values -54 & -46
I worked out a solution, however, it is \$O(n^2)\$:
for (int i = 0 ; i < A.length; i ++)
{
for (int j = i; j < A.length; j++)
{
if (abs(A[i]-A[j]) == x)
System.out.println("Indices " + i + " & " + j + " with values " + A[i] + " & "+ A[j]);
}
}
Without sorting first, is there any way to optimize this code to be faster? I know \$O(n^2)\$ isn't great but I can't think of a better way of doing it (without sorting first).
For my algorithm, the best case Omega is also \$Ω(n^2)\$, correct? I need to compare every value in any case.