Arrays and Iteration
Reverse Array In Place (Two Pointers)
Walk two indices toward each other from the ends of the array, swapping at each step. Stops when the indices meet or cross. Demonstrates the two-pointer pattern with the smallest possible state.
Algorithm
Canonical input (1, 2, 3, 4, 5, 6, 7) (odd length, middle element
stays put) yields three swap frames and reverses to
[7, 6, 5, 4, 3, 2, 1].
Basic Implementation
basic.pl
use strict; use warnings;
my @arr = (1, 2, 3, 4, 5, 6, 7);
my $left = 0;
my $right = scalar(@arr) - 1;
while ($left < $right) {
my $tmp = $arr[$left];
$arr[$left] = $arr[$right];
$arr[$right] = $tmp;
$left = $left + 1;
$right = $right - 1;
}
print "[" . join(", ", @arr) . "]\n";
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Perl: explicit three-line
my $tmp = $arr[$left]; $arr[$left] = $arr[$right]; $arr[$right] = $tmpswap keeps the move visible. The stdlibreverse @arrwould hide the lesson entirely (and returns a new list rather than mutating in place), and@arr[$left, $right] = @arr[$right, $left](list-slice assignment) would collapse the swap into a single frame. $left = 0and$right = scalar(@arr) - 1use plain integer indices; the$left < $rightguard handles the meet-in-the-middle exit honestly for the odd-length canonical input.- The replay distinguishes swap frames from pointer-advance frames so
the viewer can see
$leftand$rightconverge.
two pointers
`$left` starts at index `0`, `$right` starts at `scalar(@arr) - 1`. Each loop iteration swaps `$arr[$left]` and `$arr[$right]` and moves the pointers toward each other.