AP® Computer Science A · Unit 4 · Topic 4.5
Shifting, Rotating, and Reversing an Array
Shifting, rotating, and reversing all move array values to new index positions using a loop; the direction you loop in decides whether you overwrite data by accident or preserve it correctly.
Shifting an array right by one means every element moves to the index one higher than it started. The trap is loop direction. If you loop from index 0 upward, you copy a[0] into a[1], but then when you reach index 1 you copy that same value (which was really the old a[0]) into a[2] — you have overwritten a[1] before ever reading its original value. The fix is to loop from the last index down to 0, so each element is copied into its new spot before it gets overwritten. That is the intuition behind 'start from the right-hand end': you must move elements out of the way in an order that never destroys data you still need.
Rotating works like shifting but with one extra step: the element that would fall off the end gets saved in a temporary variable first, then placed into the now-empty spot at the front (or back, for a left rotation). Nothing is lost; it just wraps around.
Reversing uses a different pattern: two pointers, one at each end, swapping values and moving toward the middle. This connects shifting and reversing to the same family of index arithmetic used in searching and sorting later in the unit — all of them depend on careful control of loop bounds and direction to avoid off-by-one errors or lost data.
Key terms
- Shift
- Moving every element in an array a fixed number of positions left or right, losing values that fall off the end.
- Rotate
- A shift where the element that would fall off one end is wrapped around and placed at the other end instead.
- Reverse
- Reordering an array so the last element becomes first and the first becomes last, typically done by swapping from both ends inward.
- Two-pointer swap
- A technique using one index starting at each end of the array, swapping and moving toward the middle.
Watch it explained
- How it worksHow does a shift overwrite an element unless the loop runs in the right direction?
- Worked exampleTrace shifting {1, 2, 3, 4, 5} one place to the right and find which value gets lost.
- Worked exampleTrace reversing {1, 2, 3, 4, 5} by swapping from both ends toward the middle.
- Going furtherWhat changes when a rotate has to wrap the last element around to the front?
Check yourself
End of topic.