in reply to
Re: Patience Sorting To Find Longest Increasing Subsequence
in thread Patience Sorting To Find Longest Increasing Subsequence
TedPride,
Per our /msg conversation, here is a version of my implementation that uses a binary search:
sub Long_Inc_Sub {
my @list = @_;
my (@pile, @seq);
for my $num (@list) {
if (@pile) {
if ($num < $pile[-1][-1][VAL]) {
my ($beg, $end) = (0, $#pile);
while ($beg <= $end) {
my $mid = int(($beg + $end) / 2);
if ($num < $pile[$mid][-1][VAL]) {
$end = $mid - 1;
}
else {
$beg = $mid + 1;
}
}
my $prev = $beg ? $#{$pile[$beg - 1]} : undef;
push @{$pile[$beg]}, [$num, $prev];
}
else {
push @pile, [[$num, $#{$pile[-1]}]];
}
}
else {
push @pile, [[$num, undef]];
}
}
my ($prev, $len) = ($#{$pile[-1]}, scalar @pile);
while ($len--) {
$seq[$len] = $pile[$len][$prev][VAL];
$prev = $pile[$len][$prev][PREV];
}
return @seq;
}
It does not currently handle exact matches since there should not be any duplicates in the list (1..N). I did leave this open as a question to ponder and it should be fairly trivial to adapt if you decide it is safe to do so ;-)