Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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 ( [id://1084819]=note: print w/replies, xml ) Need Help??


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

Add use sort 'stable'; to ensure you get the correct result.
  • Comment on Re^2: move all 0s in an array to the beginning keeping other elements order same
  • Download Code

Replies are listed 'Best First'.
Re^3: move all 0s in an array to the beginning keeping other elements order same
by Laurent_R (Canon) on May 04, 2014 at 11:39 UTC
    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

        Thank you, Dave, for your answer, but I think that the merge sort algorithm is inherently stable, independently of its specific implementations. But you are probably right that it is better not to take any cnance and make sure that stability is guaranteed.
Re^3: move all 0s in an array to the beginning keeping other elements order same
by BillKSmith (Monsignor) on May 02, 2014 at 21:36 UTC
    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://1084819]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-20 04:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found