Can someone explain why this algorithm O(n^2)? According to this , this is O (n ^ 2). The reason I think O (n ^ 3) is because the outer loop (for x) runs nonce, the inner loop (for y) runs n-1once, and in the script the worst one, for example A = [8, 100, 101, 102, 103, 104, 105, 106, 107], while ((for z) will be run n-2once, in general O(n^3).
For completeness A, a sorted array with positive elements, the triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.
int TrianglesCount(int[] A)
{
int result = 0;
for (int x = 0; x < A.Length; x++)
{
int z = x + 2;
for (int y = x + 1; y < A.Length; y++)
{
while (z < A.Length && A[x] + A[y] > A[z])
z++;
result += z - y - 1;
}
}
return result;
}
source
share