http://www.perlmonks.org?node_id=998076

jospan has asked for the wisdom of the Perl Monks concerning the following question:

Oh Elders of Perldom, Wizards of Code and Masters of the Divine Editor enligthen a simple novice please! :)

I have an array (hereafter known as The Master Array).

The array is sorted.

I produce new arrays as subsets of The Master Array by using grep.

My question(s) is this:

1) will the subset arrays still be sorted as The Master Array or will I have to re-sort the subset arrays if I wish to ensure that these are sorted?

2) Whatever the answer to 1): can the answer be generalized to all cases where a function (say map) is used to produce arrays from a sorted master array?

  • Comment on Will the sorting order of an array used in producing new arrays be retained?

Replies are listed 'Best First'.
Re: Will the sorting order of an array used in producing new arrays be retained?
by hippo (Bishop) on Oct 09, 2012 at 21:21 UTC

    Very quick answers:

    1. Yes.
    2. Yes, so long as your function doesn't monkey with the order.

    Good luck!

Re: Will the sorting order of an array used in producing new arrays be retained?
by AnomalousMonk (Archbishop) on Oct 09, 2012 at 22:24 UTC

    For question 1: In general, WRT grep (which can only remove elements): yes, the relative order is maintained. For Far More Than You Ever Wanted to Know about this, see the recent Order in which grep/map receive elements.

    For question 2: In general, WRT map (which is allowed to insert elements) the answer is no:

    >perl -wMstrict -le "my @sorted = (1, 2, 3, 4, 5, 6); my @unsorted = map { $_, 99 } @sorted; print qq{@unsorted}; " 1 99 2 99 3 99 4 99 5 99 6 99
      Thank you both for the quick reply - I appreciate it!
Re: Will the sorting order of an array used in producing new arrays be retained?
by linuxkid (Sexton) on Oct 09, 2012 at 22:53 UTC

    Define 'Divine Editor.' You do mean Emacs right?

    --linuxkid


    imrunningoutofideas.co.cc
      I sense the dawning of yet another flame war! :D .. allow me to defuse it: 'Divine Editor' <= insert your personal favourite editor here...