Wow. (Update: I guess you are thinking of C arrays not Perl arrays, or at least an implementation much more like a naive, dynamic C array than what Perl actually uses.)

I'll agree with pop and shift being O(1) and not just in an average case. They are always O(1). (I won't argue with whether O() notation implies worst case or average case or whatever, mostly because I don't care.)

I'll agree with splice being O(N). Splicing to remove from the middle is always O(N/2). Splicing at position J elements from either end if often O(J). But splicing to insert K elements can be O(N+K). So averaging out to O(N) isn't a bad summary. Continuing to ignore some predicted objections to misuse of O(), I'd say splicing to remove is O(N/2) while splicing to insert is O(N+K). :)

If you push N times, then that is O(2*N), O(N) for the realloc() calls that likely end up copying the elements each time the array size doubles and O(N) for the N items being pushed. So push is O(2) on average. And using push on an array that both shrinks and grows is closer to O(1) than O(2) (yes, I'm still ignoring it).

If you unshift N times, then that is a bit more complex. I don't have swapped in the exact algorithm that is used for "leave some space at the front in case they unshift again", but I think it is also exponential (or is that "geometric"?) so unshift probably averages to O(3).

See Shift, Pop, Unshift and Push with Impunity! for another take on this.

- tye        


In reply to Re^5: Array VS Linked List (O) by tye
in thread Array VS Linked List by asset

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.