February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Before v5.8, quicksort was the default algorithm for Perl’s
built-in sort function. The
quicksort algorithm has at its worst quadratic behavior, and it doesn’t
necessarily preserve the order of elements that sort the same (so it’s
unstable). Perl v5.8 changed the default to a merge
sort, which at its worst has O(n·log
n) behavior and preserves the order of equal elements
(so it’s stable).
The sort pragma lets you choose
which algorithm to use. And in case the default might someday change from
a mergesort, you can choose a stable
sort without picking the particular algorithm:
use sort "stable"; # guarantee stability
use sort "_quicksort"; # use a quicksort algorithm
use sort "_mergesort"; # use a mergesort algorithm
use sort "defaults"; # revert to default behavior
no sort "stable"; # stability not important
use sort "_qsort"; # alias for quicksort
my $current;
BEGIN {
$current = sort::current(); # identify prevailing algorithm
}Read now
Unlock full access