Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: move all 0s in an array to the beginning keeping other elements order same

by BillKSmith (Chaplain)
on May 02, 2014 at 12:08 UTC ( #1084781=note: print w/ replies, xml ) Need Help??


in reply to move all 0s in an array to the beginning keeping other elements order same

One more variation on sort:

use strict; use warnings; my @array = (3, 5, 0, 0, 7, 7, 0, 8, 2, 0, 1, 8, 4); my @sorted_array = sort {($a xor $b) ? ($a <=> $b) : 0 } @array; print "@sorted_array\n";
Bill


Comment on Re: move all 0s in an array to the beginning keeping other elements order same
Download Code
Re^2: move all 0s in an array to the beginning keeping other elements order same
by ikegami (Pope) on May 02, 2014 at 17:07 UTC
    Add use sort 'stable'; to ensure you get the correct result.
      Thanks, I forgot about stability, especially when my single test case workeed correctly.
      Bill
      Hi ikegami,

      can you please explain why using the use sort 'stable'; pragma would be important? Admittedly, the sorting block is peculiar and treats non 0 values as equal so that non 0 values may be reshuffled in the process (as would be the case using quick sort). However, since Perl 5.8, the default sorting algorithm (merge sort) is inherently stable, so I would expect the order of non 0 values to be preserved. Is there anything that I am missing?

        Possibly the fact that sort internally uses a stable merge sort is an implementation detail, not a semantic guarantee. Specifying stable explicitly means that if the luck of implementation changes the semantics will still remain in tact.


        Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (9)
As of 2014-07-28 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (193 votes), past polls