Walk two indices toward each other from the ends of the vector, swapping at each step. Stops when the indices meet or cross. Demonstrates the two-pointer pattern with the smallest possible state.

Algorithm

Canonical input c(1, 2, 3, 4, 5, 6, 7) (odd length, middle element stays put) yields three swap frames and reverses to c(7, 6, 5, 4, 3, 2, 1).

Basic Implementation

basic.R
arr <- c(1, 2, 3, 4, 5, 6, 7)
left <- 1
right <- length(arr)
while (left < right) {
	tmp <- arr[left]
	arr[left] <- arr[right]
	arr[right] <- tmp
	left <- left + 1
	right <- right - 1
}
cat("[", paste(arr, collapse = ", "), "]\n", sep = "")

Complexity

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

Implementation notes

  • R: explicit three-line tmp <- arr[left]; arr[left] <- arr[right]; arr[right] <- tmp swap keeps the move visible. The stdlib rev(arr) returns a fresh vector instead of mutating, and arr[c(left, right)] <- arr[c(right, left)] (vectorised swap) would collapse the move into a single frame.
  • left <- 1 and right <- length(arr) use plain integer indices; the length() call returns the fixed length of the canonical vector.
  • 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 `length(arr)`. Each loop iteration swaps `arr[left]` and `arr[right]` and moves the pointers toward each other.