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