OlveraeUNSW
Back to problems
COMP2521

Arrays: Reverse In Place

Arrays: reverse in place (two pointers)

Reverse an array in place and print it — without allocating a second array, swap elements from the two ends inward.

Use two pointers: i starts at the front (index 0) moving right, j starts at the back (index n-1) moving left; each step swap a[i] with a[j], then i++, j--, until the pointers meet.

Complete reverse.

Pitfalls: (1) the loop condition is i < j, not i <= j — with i <= j an odd n swaps the middle element with itself (harmless but pointless), and worse, writing i <= n runs off the end. (2) Do not move both ends with the same variable; forgetting j-- loops forever. (3) For n of 0 or 1 no swap is needed, and i < j skips the loop naturally.

Input

  • Line 1: integer n (may be 0).
  • Line 2: n integers.

Output

  • One line: the reversed array, a space after each value.

Example: input 5 / 1 2 3 4 5 -> 5 4 3 2 1 .

Samples

stdin
5
1 2 3 4 5
expected
5 4 3 2 1 
stdin
1
42
expected
42 
c-dcc
14