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 arr=(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.sh
#!/usr/bin/env bash
set -euo pipefail
arr=(1 2 3 4 5 6 7)
left=0
right=$(( ${#arr[@]} - 1 ))
while [ "$left" -lt "$right" ]; do
tmp=${arr[left]}
arr[left]=${arr[right]}
arr[right]=$tmp
left=$((left + 1))
right=$((right - 1))
done
printf '['
sep=''
for v in "${arr[@]}"; do
printf '%s%d' "$sep" "$v"
sep=', '
done
printf ']\n'
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Bash: explicit three-line
tmp=${arr[left]}; arr[left]=${arr[right]}; arr[right]=$tmpswap keeps the move visible. The shell has no built-in reverse for arrays; spawningprintf '%s\n' "${arr[@]}" | tacwould push the work to another process and return a stream instead of mutating the array. left=0andright=$(( ${#arr[@]} - 1 ))use plain integer indices;${#arr[@]}returns the fixed length of the canonical array.- The replay distinguishes swap frames from pointer-advance frames so
the viewer can see
leftandrightconverge.
two pointers
`left` starts at index `0`, `right` starts at `${#arr[@]} - 1`. Each loop iteration swaps `arr[left]` and `arr[right]` and moves the pointers toward each other.