XP is just a number | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Hello QuillMeantTen, and welcome to the Monastery! Since this is a learning exercise, I want to comment on your use of C-style for loops. For example, from sub heapify:
As a general rule, whenever you have a C-style for loop in which the reinitialisation expression increments a variable by one, you should re-cast it as a Perl-style foreach loop instead:
Or, even better, put it on a single line by making the foreach a statement modifier:
— which has the added advantage of simplifying the code by removing a variable declaration. Not only is a Perl foreach loop intrinsically faster than its C-style equivalent; in this case you get a significant extra benefit in efficiency, because the subroutine call to leonardo($order) is made only once. Here’s a longer example to emphasise the point:
Output:
Of course, this works only because the value returned by leonardo($order) doesn’t change (because $order isn’t changed in the body of the loop). Another point to note: recursive functions like sub leonardo can often be significantly streamlined by memoization. This is explained in Chapter 3 of Higher-Order Perl by Mark Jason Dominus, which is available for free from http://hop.perl.plover.com/. See also the module Memoize (also by MJD). Update: Fixed off-by-one error in foreach loops, thanks to AnomalousMonk (twice!). Hope that helps,
In reply to Re: Smoothsort
by Athanasius
|
|