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 isi < j, noti <= j— withi <= jan oddnswaps the middle element with itself (harmless but pointless), and worse, writingi <= nruns off the end. (2) Do not move both ends with the same variable; forgettingj--loops forever. (3) Fornof 0 or 1 no swap is needed, andi < jskips the loop naturally.
Input
- Line 1: integer
n(may be0). - Line 2:
nintegers.
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