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.rs
fn main() {
	let mut arr = [1, 2, 3, 4, 5, 6, 7];
	let mut left = 0usize;
	let mut right = arr.len() - 1;
	while left < right {
		let tmp = arr[left];
		arr[left] = arr[right];
		arr[right] = tmp;
		left = left + 1;
		right = right - 1;
	}
	println!("{:?}", arr);
}

Complexity

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

Implementation notes

  • Rust: explicit three-line let tmp = ...; arr[left] = arr[right]; arr[right] = tmp; swap keeps the move visible. The standard arr.swap(left, right) and Vec::reverse would hide the lesson.
  • let mut left = 0usize; and let mut right = arr.len() - 1; use plain usize indices; the left < right guard handles the meet-in-the-middle exit honestly for the odd-length canonical input.
  • The replay shows both left and right, the values about to be swapped, and the array contents after the swap. The loop-exit frame is the moment the pointers meet.
two pointers `left` starts at index `0`, `right` starts at `n - 1`. Each loop iteration swaps `arr[left]` and `arr[right]` and moves the pointers toward each other.