Array Rotation in C
This program demonstrates how to rotate an array by k
positions using the C programming language. The rotation is performed in-place to optimize memory usage.
Explanation of the Program
The array rotation is performed by breaking the problem into three steps:
- Reverse the first part of the array (from index 0 to
k-1
). - Reverse the second part of the array (from index
k
ton-1
). - Reverse the entire array (from index 0 to
n-1
).
By reversing these parts of the array, the elements are effectively rotated by k
positions.
C Program
#include <stdio.h>
void reverse(int arr[], int start, int end) {
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void rotateArray(int arr[], int n, int k) {
// Handle cases where k is larger than n
k = k % n;
// Reverse the first part of the array
reverse(arr, 0, k - 1);
// Reverse the second part of the array
reverse(arr, k, n - 1);
// Reverse the entire array
reverse(arr, 0, n - 1);
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
printf("Original array:\n");
printArray(arr, n);
rotateArray(arr, n, k);
printf("Array after rotation by %d positions:\n", k);
printArray(arr, n);
return 0;
}
Program Output
Original array: 1 2 3 4 5 6 7 Array after rotation by 3 positions: 4 5 6 7 1 2 3
Conclusion
This program effectively rotates an array by k
positions using a series of three reverse operations. This approach ensures that the rotation is done in-place, optimizing memory usage while maintaining a time complexity of O(n)
.