Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

by BillKSmith (Monsignor)
on May 02, 2014 at 12:08 UTC ( [id://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

Replies are listed 'Best First'.
Re^2: move all 0s in an array to the beginning keeping other elements order same
by ikegami (Patriarch) on May 02, 2014 at 17:07 UTC
    Add use sort 'stable'; to ensure you get the correct result.
      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

      Thanks, I forgot about stability, especially when my single test case workeed correctly.
      Bill

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-18 12:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found