Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

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


in reply to Re^2: 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

ow! You transformed a O(N) problem into an O(N2) solution.
firstidx starts at the start of the array every loop pass.

Not only did you half the speed, you doubled the memory requirements.
"firstidx" copies the entire array before processing it.

Replies are listed 'Best First'.
Re^4: Testing if an array contains a value and then deleting it in most efficient way
by parv (Parson) on Feb 18, 2008 at 16:40 UTC

    How can you avoid O(N^2) cost if using unsorted array? So far there is no indication whether it would be sorted. (Addendum: I wasn't thinking so just quoted the O(N^2) cost, which really should have been O(N). Time to sleep belatedly, I suppose.)

    I thought that List::MoreUtils::firstidx would use XS magic (to avoid copying). No? (I would have looked inside the C code myself but am not familiar with XS yet.)

    Later ... I see now that array might be already sorted (and first element would be the interesting one).

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

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-25 23:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found