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