in reply to Re^7: Longest Increasing Subset
in thread Longest Increasing Subset

I also implemented the wiki pseudo-code, resulting almost identical code:

#! perl -slw use strict; use Time::HiRes qw[ time ]; use Data::Dump qw[ pp ]; $Data::Dump::WIDTH = 500; our $S //= 0; srand $S if $S; our $N //= 20; sub LIS { my $X = shift; my( @P, @M ); my $L = 0; for my $i ( 0 .. $#$X ) { ## Binary search for the largest positive j = L such that X[M[ +j]] < X[i] my $lo = 1; my $hi = $L; while( $lo <= $hi ) { my $mid = int( ( $lo + $hi ) / 2 ); if( $X->[ $M[ $mid ] ] < $X->[ $i ] ) { $lo = $mid + 1; } else{ $hi = $mid - 1; } } ## After searching, lo is 1 greater than the length of the lon +gest prefix of X[i] my $newL = $lo; ## The predecessor of X[i] is the last index of the subsequenc +e of length newL-1 $P[ $i ] = $M[ $newL - 1 ]; $M[ $newL ] = $i; if( $newL > $L ) { ## If we found a subsequence longer than any we've found y +et, update L $L = $newL; } } ## Reconstruct the longest increasing subsequence my @S; my $k = $M[ $L ]; for my $i ( reverse 0 .. $L-1 ) { $S[ $i ] = $X->[ $k ]; $k = $P[ $k ]; } return @S; } my @data = map int( rand $N ), 1 .. $N; my $start = time; my @best = LIS( \@data ); printf "best(%d): @best\n", scalar @best; printf "Took %.3f seconds\n", time() - $start;

Though I pass the data in via a reference for efficiency.

I've been trying to wrap my brain around the mentioned Knuth optimisation without success.

One comment on your code. This return wantarray ? @S : [@S]; throws away the advantage of returning a reference, by constructing a list from the existing array, which is then used to construct another (anonymous) array, a reference to which is returned.

Better to just do return wantarray ? @S : \@S;


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice.