Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.

Algorithm

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.

Basic Implementation

basic.pl
Replay: real traced execution (multi-file project)
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";
  1. arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3

    1use strict;2use warnings;
    values this step[3, 1, 4, 1, 5, 9, 2, 6]arr3best
  2. replaced ← no

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this stepnoreplaced1i1arr[i]3best
  3. best ← 4, replaced ← yes

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this step3 4bestyesreplaced2i4arr[i]
  4. replaced ← no

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this stepnoreplaced3i1arr[i]4best
  5. best ← 5, replaced ← yes

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this step4 5bestyesreplaced4i5arr[i]
  6. best ← 9, replaced ← yes

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this step5 9bestyesreplaced5i9arr[i]
  7. replaced ← no

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this stepnoreplaced6i2arr[i]9best
  8. replaced ← no

    5for (my $i = 1; $i < @arr; $i++) {6	if ($arr[$i] > $best) {7		$best = $arr[$i];
    values this stepnoreplaced7i6arr[i]9best
  9. stdout ← 9

    9}10print "$best\n";
    values this step9stdout9best

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, @arr is 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 $best at 3 for index 1, updates to 4 at index 2, stays 4 at index 3, updates to 5 at index 4, and updates to 9 at index 5.
  • The final checks at indexes 6 and 7 see 2 and 6, so $best remains 9.
  • print "$best\n" interpolates the scalar into a string and prints the final output line 9.