in reply to Is sorting different in Perl 5.6.1 than in Perl 5.8.8?

Perl's sort() is not guaranteed to be stable.

Perls v5.6 and earlier did not use a stable sort. Current perls (probably) do can use a stable sort, but by default probably don't (this is from the docs of the sort pragma: I haven't tested it**). From the current sort (function) docs:

Perl 5.6 and earlier used a quicksort algorithm to implement sort. That algorithm was not stable, and could go quadratic. (A stable sort preserves the input order of elements that compare equal. Although quicksort's run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), quadratic behavior, for some inputs.) In 5.7, the quicksort implementation was replaced with a stable mergesort algorithm whose worst-case behavior is O(NlogN). But benchmarks indicated that for some inputs, on some platforms, the original quicksort was faster. 5.8 has a sort pragma for limited control of the sort. Its rather blunt control of the underlying algorithm may not persist into future Perls, but the ability to characterize the input or output in implementation independent ways quite probably will. See sort.
In other words, if you want to have a stable sort, you need a 5.8+ perl and use the sort pragma.

** update (again):

> perl -Msort=defaults -e'print sort::current' mergesort
on my system (debian linux, perl5.8.8) which as I understand it means sort is stable by default on that perl.

Replies are listed 'Best First'.
Re^2: Is sorting different in Perl 5.6.1 than in Perl 5.8.8?
by frostman (Beadle) on Nov 01, 2007 at 01:44 UTC

    Ah, interesting, thanks.

    That pretty much answers the basic question, and in my real-life implementation I'm lucky enough to be able to demand a "tiebreaker" be specified if you care about sort stability.