DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES
Rotate an Array with the Reversal Algorithm
Rotate an array left by two positions using three in-place reversals.
PROBLEM UNDERSTANDING
Input and expected output
No input required
3 4 5 6 7 1 2
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void reverse(int values[], int left, int right)
{
while (left < right) {
int temporary = values[left];
values[left++] = values[right];
values[right--] = temporary;
}
}
int main(void)
{
int values[] = {1, 2, 3, 4, 5, 6, 7};
int length = 7, positions = 2;
reverse(values, 0, positions - 1);
reverse(values, positions, length - 1);
reverse(values, 0, length - 1);
for (int index = 0; index < length; index++) printf("%d ", values[index]);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
3 4 5 6 7 1 2
PROGRAM EXPLANATION
Algorithm and explanation
- Start with {1, 2, 3, 4, 5, 6, 7}; length is 7 and positions is 2.
- Reverse indices 0 through 1 to get {2, 1, 3, 4, 5, 6, 7}.
- Reverse indices 2 through 6 to get {2, 1, 7, 6, 5, 4, 3}.
- Reverse the whole array to get {3, 4, 5, 6, 7, 1, 2}, then print it.
Write the array as two segments A and B, where A contains the first k elements. Reversing A, then B, then the complete array transforms reverse(A) + reverse(B) into B + A. Each reversal swaps the two outer elements and moves the endpoints inward. The total work is O(n), and the temporary variable needs O(1) auxiliary space. The supplied example uses a fixed array and does not read input. Its indices are valid for 0 <= positions <= length. For a general API with length > 0, normalize a non-negative rotation count using positions %= length; handle an empty array before taking the remainder.
EFFICIENCY
Time and space complexity
O(n)
O(1)
DEBUGGING CHECKLIST
Common mistakes
This is a left rotation: do not expect the output of a right rotation.
Keep the first segment endpoint at positions - 1; using positions reverses one extra element.
Do not use positions greater than length with these calls: the first reversal can access outside the array.
