Arrays and Iteration
Find Maximum
Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.
Algorithm
Basic Implementation
basic.pl
use strict;
use warnings;
my @arr = (3, 1, 4, 1, 5, 9, 2, 6);
my $best = $arr[0];
for (my $i = 1; $i < @arr; $i++) {
if ($arr[$i] > $best) {
$best = $arr[$i];
}
}
print "$best\n";
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
my @arr = (3, 1, 4, 1, 5, 9, 2, 6)declares the pinned Perl array with the@sigil.my $best = $arr[0]seeds the scalar running maximum from the first slot, so the replay starts with$best = 3.- The scan uses an indexed C-style loop:
for (my $i = 1; $i < @arr; $i++). - In the loop condition,
@arris used in scalar context, so it behaves as the array length. - Each candidate is read as
$arr[$i]; the array keeps the@sigil in the declaration, but individual elements use$. - The comparison is numeric:
if ($arr[$i] > $best). - Assignment only happens inside that
if, with$best = $arr[$i]. - The trace keeps
$bestat3for index1, updates to4at index2, stays4at index3, updates to5at index4, and updates to9at index5. - The final checks at indexes
6and7see2and6, so$bestremains9. print "$best\n"interpolates the scalar into a string and prints the final output line9.
execution replay
The checked-in replay follows the language-neutral state table for `array-find-max`.
cross-language comparison
This Perl DSA version keeps the same data and final output as every other DSA book in this wave.