Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Sorting Array in Place

by dbp (Pilgrim)
on Nov 24, 2002 at 23:22 UTC ( #215550=perlquestion: print w/replies, xml ) Need Help??
dbp has asked for the wisdom of the Perl Monks concerning the following question:

Is there an idiomatic way to sort an array in place in Perl? As far as I understand,
my @list = sort @list;
incurs the overhead of creating a new array and copying the values into @list; we get the same result as sorting a list in place but at greater cost. It is conceivable that Perl is optimized to take advantage of code like this, but I don't know one way or another. One could easily write a sub that performs some sorting algorithm (quicksort, mergesort, etc) on an array reference, but is there a way to coerce Perl's built-in functions to get the desired effect?

Replies are listed 'Best First'.
Re: Sorting Array in Place
by dws (Chancellor) on Nov 24, 2002 at 23:57 UTC
    Is there an idiomatic way to sort an array in place in Perl?

    No. There are ways to do in-place sorts, but they're not idiomatic.

Re: Sorting Array in Place
by pg (Canon) on Nov 25, 2002 at 00:02 UTC
    Agree, it will be nice if sort behaves in such a way:
    1. if the parm being passed in is a list, behave in the traditional way;
    2. if the parm being passed in is a ref to an array, do an in-place sort as you suggested.
      Well, I'm toying with the idea of a module that provides a sort_inplace function which acts a lot like sort but takes array references as a sort of stop-gap solution. Is there any way to get $a and $b to represent the first two values of @_ as in sort? See my scratchpad for some code and a more detailed description.
Re: Sorting Array in Place
by Anonymous Monk on Oct 29, 2012 at 19:46 UTC
    For the record, as of perl 5.10 (see the In place sorting section of the changelog), assigning the results of sort on an array to the same array is optimized to do an in-place sort.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://215550]
Approved by gjb
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2018-03-24 18:09 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (299 votes). Check out past polls.