in reply to quick sort. How do it faster
With just a few syntax changes (no change to the logic) I can shave off about 8% of the run time...
sub sortQ2 { my ($s, $e, $dst) = @_; my $m = $s - 1; ($dst->[$_] < $dst->[$e]) && ( ++$m, ($dst->[$m], $dst->[$_]) = ($dst->[$_], $dst->[$m]), ) for ($s .. $e-1); ++$m; ($dst->[$m], $dst->[$e]) = ($dst->[$e], $dst->[$m]); sortQ2($s, $m-1, $dst) if ($s < $m - 1); sortQ2($m+1, $e, $dst) if ($m + 1 < $e); }
How does this speed things up? Each pair of { ... } introduces a lexical scope; scopes have a small runtime overhead. I've removed all of them except for the one surrounding the entire function.
You can get a few percent extra using Data::Alias which allows you to avoid some arrayref dereferencing operations:
use Data::Alias; sub sortQ2 { my ($s, $e, $dst) = @_; alias my @dst = @$dst; my $m = $s - 1; ($dst[$_] < $dst[$e]) && ( ++$m, ($dst[$m], $dst[$_]) = ($dst[$_], $dst[$m]), ) for ($s .. $e-1); ++$m; ($dst[$m], $dst[$e]) = ($dst[$e], $dst[$m]); ($s < $m - 1) && sortQ2($s, $m-1, $dst); ($m + 1 < $e) && sortQ2($m+1, $e, $dst); }
Overall, this is about 12% faster than the original.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: quick sort. How do it faster
by BrowserUk (Patriarch) on Oct 20, 2013 at 11:08 UTC | |
by tobyink (Canon) on Oct 23, 2013 at 13:50 UTC | |
by BrowserUk (Patriarch) on Oct 23, 2013 at 16:31 UTC | |
by LanX (Saint) on Oct 24, 2013 at 12:41 UTC |