in reply to Shifting an Array

The latter more or less does the same work as the former. However, the latter does all the work in Perl, while the former does it in C. However, the usual way of doing this is by using splice, which also does the same work, and also in C:
splice @a => $idx, 0 => $newitem;
Note that they all take time linear in the size of the array. If you need to do a lot of insertions in a long list, you ought to review your algorithm, and see whether you really need to keep a sorted list. Perhaps a (balanced) tree will be better.

Abigail

Replies are listed 'Best First'.
Re: Re: Shifting an Array
by kelan (Deacon) on Aug 30, 2002 at 13:00 UTC
    Note that they all take time linear in the size of the array. If you need to do a lot of insertions in a long list, you ought to review your algorithm, and see whether you really need to keep a sorted list. Perhaps a (balanced) tree will be better.

    I considered something like that, but I don't think it will be worth the extra complexity in this situation. Insertions (and deletions) won't be happening anywhere near as often as ordered processing of the list, which is easiest with a sorted array like this.

    I'm also curious as to how Perl does slices internally if the loop version and the slice version are more or less the same. I'd assumed that a slice becomes an anonymous list, with copies of the original values. Wouldn't that take more time to setup than just iterating through the existing one?

    Thanks for the splice tip. I wasn't aware of it:)

      I'm also curious as to how Perl does slices internally if the loop version and the slice version are more or less the same. I'd assumed that a slice becomes an anonymous list, with copies of the original values. Wouldn't that take more time to setup than just iterating through the existing one?
      But during your iteration, you are assigning as well - so you are making copies as well.

      Abigail