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.lua
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")

Complexity

  • Time: O(n)
  • Space: O(1)

Implementation notes

  • Lua: explicit three-line local tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp swap keeps the move visible. Lua has no stdlib reverse for tables, but a for loop with arr[i], arr[#arr - i + 1] = arr[#arr - i + 1], arr[i] (parallel assignment) would collapse the swap into a single frame.
  • left = 1 and right = #arr use 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 left and right converge.
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.