Reverse Array
Two pointers swap inward from both ends
Reversing doesn't need a second array or repeated shifting — swap the first and last elements, then the second and second-to-last, and so on, moving two pointers toward each other from opposite ends. Once they meet (or cross), every pair has been swapped exactly once.
Two pointers swap inward from both ends
step 1 / 5
l=0, r=4: swap the outermost pair first, then move both pointers inward until they meet.
- l=0· arr[0] = 1
- r=4· arr[4] = 5
1FUNCTION reverseArray(arr):2 l = 0, r = (the length of arr) - 13 WHILE l < r:4 swap arr[l] and arr[r]5 move l one step right; move r one step left6 RETURN arr
← / → step · space play · Home restart
Every step in words
Show all 5 steps
- l=0, r=4: swap the outermost pair first, then move both pointers inward until they meet.
- Swap arr[0] and arr[4] -> [5, 2, 3, 4, 1].
- Move inward: l=1, r=3.
- Swap arr[1] and arr[3] -> [5, 4, 3, 2, 1].
- l meets r at the middle (idx 2) — that element never needed to move. Final array: [5, 4, 3, 2, 1].
Now solve it yourself
Watching is the first half. The second is writing it without the animation.