Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^5: Testing if an array contains a value and then deleting it in most efficient way

by ikegami (Patriarch)
on Feb 18, 2008 at 16:50 UTC ( [id://668604]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Testing if an array contains a value and then deleting it in most efficient way
in thread Testing if an array contains a value and then deleting it in most efficient way

Update: No, I guess I'm wrong. The nested loops (while and firstidx confused me).


while ( -1 < ( $i = firstidx { $_ == $val } @array ) ) { ... }

is best case O(N).
is worse case O(N2).

for (0 .. $#array) { next if $_ != $var; ... }

is best, real & worse case O(N).

Replies are listed 'Best First'.
Re^6: Testing if an array contains a value and then deleting it in most efficient way
by ikegami (Patriarch) on Feb 19, 2008 at 03:59 UTC

    No, I was right.

    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).

      Note that OP did not say anything about handling of multiplicates. The inner loop is to delete all the matching values not just the first one, to be a similar solution to a hash solution (since the same key cannot occur multiple times).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://668604]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-19 07:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found