while ( -1 < ( $i = firstidx { $_ == $val } @array ) )
{
...
}
is worse case O(N2).
Take the case where the condition is true for all items.
For the first loop pass, all elements of @array are put on the stack ( time = k * N )
For the second loop pass, all remaining elements of @array are put on the stack ( time = k * (N-1) )
For the third loop pass, all remaining elements of @array are put on the stack ( time = k * (N-2) )
...
For the last loop pass, all remaining element of @array is put on the stack ( time = k * 0 )
The total time = k * ( N * (N+1) / 2 ) = O(N2)
If the language evaluated @array lazily, it would be O(N).
|