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}.
two pointers
`left` starts at index `1`, `right` starts at `#arr`. Each loop iteration swaps `arr[left]` and `arr[right]` and moves the pointers toward each other.
Basic Implementation
basic.lua
Replay: real traced execution (multi-file project)
local arr = {1, 2, 3, 4, 5, 6, 7}
local left = 1
local right = #arr
while left < right do
local tmp = arr[left]
arr[left] = arr[right]
arr[right] = tmp
left = left + 1
right = right - 1
end
io.write("[")
for i = 1, #arr do
if i > 1 then io.write(", ") end
io.write(tostring(arr[i]))
end
io.write("]\n")
arr ← [1, 2, 3, 4, 5, 6, 7]
1local arr = {1, 2, 3, 4, 5, 6, 7}2local left = 1values this step[1, 2, 3, 4, 5, 6, 7]arrleft ← 1
1local arr = {1, 2, 3, 4, 5, 6, 7}2local left = 13local right = #arrvalues this step1left[1, 2, 3, 4, 5, 6, 7]arrright ← 7
2local left = 13local right = #arr4while left < right dovalues this step7right1leftarr ← [7, 2, 3, 4, 5, 6, 1]
5local tmp = arr[left]6arr[left] = arr[right]7arr[right] = tmpvalues this step[1, 2, 3, 4, 5, 6, 7] → [7, 2, 3, 4, 5, 6, 1]arr1left7rightleft ← 2
7arr[right] = tmp8left = left + 19right = right - 1values this step1 → 2leftright ← 6
8 left = left + 19 right = right - 110endvalues this step7 → 6rightarr ← [7, 6, 3, 4, 5, 2, 1]
5local tmp = arr[left]6arr[left] = arr[right]7arr[right] = tmpvalues this step[7, 2, 3, 4, 5, 6, 1] → [7, 6, 3, 4, 5, 2, 1]arr2left6rightleft ← 3
7arr[right] = tmp8left = left + 19right = right - 1values this step2 → 3leftright ← 5
8 left = left + 19 right = right - 110endvalues this step6 → 5rightarr ← [7, 6, 5, 4, 3, 2, 1]
5local tmp = arr[left]6arr[left] = arr[right]7arr[right] = tmpvalues this step[7, 6, 3, 4, 5, 2, 1] → [7, 6, 5, 4, 3, 2, 1]arr3left5rightleft ← 4
7arr[right] = tmp8left = left + 19right = right - 1values this step3 → 4leftright ← 4
8 left = left + 19 right = right - 110endvalues this step5 → 4rightwhile left < right do
3local right = #arr4while left < right do5 local tmp = arr[left]values this step[7, 6, 5, 4, 3, 2, 1]arr4left4right
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Lua: explicit three-line
local tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmpswap keeps the move visible. Lua has no stdlibreversefor tables, but aforloop witharr[i], arr[#arr - i + 1] = arr[#arr - i + 1], arr[i](parallel assignment) would collapse the swap into a single frame. left = 1andright = #arruse plain integer indices; the#length operator returns the fixed length of the canonical array.- The replay distinguishes swap frames from pointer-advance frames so
the viewer can see
leftandrightconverge.