Array Rotation Left And Right in C
Array rotation is a fundamental operation in computer science, often used in algorithms and data manipulation.
In this article, you will learn how to perform left and right array rotations using various efficient C programming techniques.
Problem Statement
The problem of array rotation involves shifting elements of an array by a specified number of positions, either to the left or to the right. This operation is crucial in areas like image processing, cryptography, and data compression, where efficient element rearrangement is key. For instance, rotating an array [1, 2, 3, 4, 5] left by 2 positions results in [3, 4, 5, 1, 2].
Example
Let's consider an array: [1, 2, 3, 4, 5]
- Left Rotation by 2 positions: The elements
1and2move to the end. The result is[3, 4, 5, 1, 2]. - Right Rotation by 2 positions: The elements
4and5move to the beginning. The result is[4, 5, 1, 2, 3].
Background & Knowledge Prerequisites
To follow along with this article, you should have a basic understanding of:
- C programming language fundamentals (variables, data types, loops).
- Arrays in C (declaration, initialization, accessing elements).
- Functions in C (defining, calling, passing parameters).
Use Cases or Case Studies
Array rotation finds application in diverse scenarios:
- Image Processing: Rotating images often involves rotating rows or columns of pixel data.
- Cryptography: Certain encryption algorithms use bit or byte rotation to scramble data, enhancing security.
- Data Compression: Cyclic shifts can be part of data transformation techniques to reveal patterns that allow for better compression.
- Circular Buffers/Queues: Implementing data structures like circular queues or buffers where elements wrap around requires rotation logic for efficient management.
- Algorithm Optimization: Some search or pattern matching algorithms can benefit from data rotation to simplify comparisons or reduce redundant computations.
Solution Approaches
We will explore several methods for both left and right array rotations.
Left Rotation Approaches
Approach 1: Rotate One by One
One-line summary: Repeatedly rotate the array by one position d times.
// Left Rotate Array One by One
#include <stdio.h>
// Function to left rotate array by one position
void leftRotateByOne(int arr[], int n) {
int temp = arr[0]; // Store the first element
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i + 1]; // Shift elements to the left
}
arr[n - 1] = temp; // Place the stored element at the end
}
// Function to left rotate array by d positions
void leftRotate(int arr[], int n, int d) {
for (int i = 0; i < d; i++) {
leftRotateByOne(arr, n);
}
}
// Function to print array elements
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 d = 2; // Number of positions to rotate
printf("Original array: ");
printArray(arr, n);
// Step 1: Call leftRotate function to rotate the array
leftRotate(arr, n, d);
printf("Left rotated array by %d positions: ", d);
printArray(arr, n);
return 0;
}
Sample output:
Original array: 1 2 3 4 5 6 7
Left rotated array by 2 positions: 3 4 5 6 7 1 2
Stepwise explanation:
- The
leftRotateByOnefunction takes the first element, saves it in a temporary variable (temp). - It then shifts all subsequent elements one position to their left (
arr[i] = arr[i + 1]). - Finally, the saved
tempelement is placed at the last position of the array. - The
leftRotatefunction repeatedly callsleftRotateByOnedtimes to achieve a total left rotation ofdpositions.
Approach 2: Using a Temporary Array
One-line summary: Copy the first d elements to a temporary array, then shift the remaining elements, and finally append the temporary elements.
// Left Rotate Array using Temp Array
#include <stdio.h>
// Function to left rotate array by d positions using a temporary array
void leftRotateTempArray(int arr[], int n, int d) {
// Adjust d if it's greater than n to avoid unnecessary rotations
d = d % n;
// Create a temporary array to store the first 'd' elements
int temp[d];
for (int i = 0; i < d; i++) {
temp[i] = arr[i];
}
// Shift the remaining (n-d) elements to the front
for (int i = d; i < n; i++) {
arr[i - d] = arr[i];
}
// Copy the elements from the temporary array to the end of the original array
for (int i = 0; i < d; i++) {
arr[n - d + i] = temp[i];
}
}
// Function to print array elements (re-used for brevity)
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 d = 2; // Number of positions to rotate
printf("Original array: ");
printArray(arr, n);
// Step 1: Call leftRotateTempArray function to rotate the array
leftRotateTempArray(arr, n, d);
printf("Left rotated array by %d positions: ", d);
printArray(arr, n);
return 0;
}
Sample output:
Original array: 1 2 3 4 5 6 7
Left rotated array by 2 positions: 3 4 5 6 7 1 2
Stepwise explanation:
- First, the rotation count
dis adjusted (d = d % n) to handle cases wheredmight be greater than the array sizen. - A temporary array
tempof sizedis created. The firstdelements of the original array are copied intotemp. - The elements from index
dton-1are shifteddpositions to the left, filling the gap left by the firstdelements. - Finally, the elements stored in the
temparray are copied back into the original array, starting from indexn-d, effectively appending them to the end.
Approach 3: Reversal Algorithm
One-line summary: Reverse the first d elements, reverse the remaining n-d elements, then reverse the entire array.
// Left Rotate Array using Reversal Algorithm
#include <stdio.h>
// Function to reverse a subarray arr[start...end]
void reverseArray(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
// Function to left rotate array by d positions using reversal
void leftRotateReversal(int arr[], int n, int d) {
// Adjust d if it's greater than n
d = d % n;
// Step 1: Reverse the first 'd' elements
// Example: arr = [1, 2, 3, 4, 5, 6, 7], d = 2
// Reverse [1, 2] -> [2, 1, 3, 4, 5, 6, 7]
reverseArray(arr, 0, d - 1);
// Step 2: Reverse the remaining 'n-d' elements
// Example: [2, 1, 3, 4, 5, 6, 7]
// Reverse [3, 4, 5, 6, 7] -> [7, 6, 5, 4, 3]
// Array becomes: [2, 1, 7, 6, 5, 4, 3]
reverseArray(arr, d, n - 1);
// Step 3: Reverse the entire array
// Example: [2, 1, 7, 6, 5, 4, 3]
// Reverse [2, 1, 7, 6, 5, 4, 3] -> [3, 4, 5, 6, 7, 1, 2] (Left rotated)
reverseArray(arr, 0, n - 1);
}
// Function to print array elements (re-used for brevity)
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 d = 2; // Number of positions to rotate
printf("Original array: ");
printArray(arr, n);
// Step 1: Call leftRotateReversal function to rotate the array
leftRotateReversal(arr, n, d);
printf("Left rotated array by %d positions: ", d);
printArray(arr, n);
return 0;
}
Sample output:
Original array: 1 2 3 4 5 6 7
Left rotated array by 2 positions: 3 4 5 6 7 1 2
Stepwise explanation:
- The
dvalue is adjusted usingd = d % n. - The first
delements of the array (arr[0]toarr[d-1]) are reversed. - The remaining
n-delements of the array (arr[d]toarr[n-1]) are reversed. - Finally, the entire array (
arr[0]toarr[n-1]) is reversed. This sequence of reversals correctly places the elements in their left-rotated positions.
Right Rotation Approaches
Approach 1: Rotate One by One (Right)
One-line summary: Repeatedly rotate the array by one position to the right d times.
// Right Rotate Array One by One
#include <stdio.h>
// Function to right rotate array by one position
void rightRotateByOne(int arr[], int n) {
int temp = arr[n - 1]; // Store the last element
for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1]; // Shift elements to the right
}
arr[0] = temp; // Place the stored element at the beginning
}
// Function to right rotate array by d positions
void rightRotate(int arr[], int n, int d) {
for (int i = 0; i < d; i++) {
rightRotateByOne(arr, n);
}
}
// Function to print array elements (re-used for brevity)
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 d = 2; // Number of positions to rotate
printf("Original array: ");
printArray(arr, n);
// Step 1: Call rightRotate function to rotate the array
rightRotate(arr, n, d);
printf("Right rotated array by %d positions: ", d);
printArray(arr, n);
return 0;
}
Sample output:
Original array: 1 2 3 4 5 6 7
Right rotated array by 2 positions: 6 7 1 2 3 4 5
Stepwise explanation:
- The
rightRotateByOnefunction saves the last element of the array intemp. - It then shifts all preceding elements one position to their right (
arr[i] = arr[i - 1]). - Finally, the saved
tempelement is placed at the first position of the array. - The
rightRotatefunction callsrightRotateByOnedtimes to complete the rotation.
Approach 2: Using a Temporary Array (Right)
One-line summary: Copy the last d elements to a temporary array, then shift the remaining elements, and finally prepend the temporary elements.
// Right Rotate Array using Temp Array
#include <stdio.h>
// Function to right rotate array by d positions using a temporary array
void rightRotateTempArray(int arr[], int n, int d) {
// Adjust d if it's greater than n
d = d % n;
// Create a temporary array to store the last 'd' elements
int temp[d];
for (int i = 0; i < d; i++) {
temp[i] = arr[n - d + i];
}
// Shift the remaining (n-d) elements to the right
// Iterate from right to left to avoid overwriting un-shifted values
for (int i = n - 1; i >= d; i--) {
arr[i] = arr[i - d];
}
// Copy the elements from the temporary array to the beginning of the original array
for (int i = 0; i < d; i++) {
arr[i] = temp[i];
}
}
// Function to print array elements (re-used for brevity)
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 d = 2; // Number of positions to rotate
printf("Original array: ");
printArray(arr, n);
// Step 1: Call rightRotateTempArray function to rotate the array
rightRotateTempArray(arr, n, d);
printf("Right rotated array by %d positions: ", d);
printArray(arr, n);
return 0;
}
Sample output:
Original array: 1 2 3 4 5 6 7
Right rotated array by 2 positions: 6 7 1 2 3 4 5
Stepwise explanation:
- The rotation count
dis adjusted (d = d % n). - A temporary array
tempof sizedis created. The lastdelements of the original array (arr[n-d]toarr[n-1]) are copied intotemp. - The elements from index
n-1down todare shifteddpositions to the right, creating space at the beginning. - Finally, the elements from the
temparray are copied back into the original array, starting from index0, thus prepending them.
Approach 3: Reversal Algorithm (Right)
One-line summary: Reverse the entire array, then reverse the first d elements, and finally reverse the remaining n-d elements.
// Right Rotate Array using Reversal Algorithm
#include <stdio.h>
// Function to reverse a subarray arr[start...end] (re-used for brevity)
void reverseArray(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
// Function to right rotate array by d positions using reversal
void rightRotateReversal(int arr[], int n, int d) {
// Adjust d if it's greater than n
d = d % n;
// Step 1: Reverse the entire array
// Example: arr = [1, 2, 3, 4, 5, 6, 7], d = 2
// Reverse [1,2,3,4,5,6,7] -> [7,6,5,4,3,2,1]
reverseArray(arr, 0, n - 1);
// Step 2: Reverse the first 'd' elements
// Example: [7,6,5,4,3,2,1]
// Reverse [7,6] -> [6,7,5,4,3,2,1]
reverseArray(arr, 0, d - 1);
// Step 3: Reverse the remaining 'n-d' elements
// Example: [6,7,5,4,3,2,1]
// Reverse [5,4,3,2,1] -> [1,2,3,4,5]
// Array becomes: [6,7,1,2,3,4,5] (Right rotated)
reverseArray(arr, d, n - 1);
}
// Function to print array elements (re-used for brevity)
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 d = 2; // Number of positions to rotate
printf("Original array: ");
printArray(arr, n);
// Step 1: Call rightRotateReversal function to rotate the array
rightRotateReversal(arr, n, d);
printf("Right rotated array by %d positions: ", d);
printArray(arr, n);
return 0;
}
Sample output:
Original array: 1 2 3 4 5 6 7
Right rotated array by 2 positions: 6 7 1 2 3 4 5
Stepwise explanation:
- The
dvalue is adjusted usingd = d % n. - The entire array (
arr[0]toarr[n-1]) is reversed. - Then, the first
delements of the now-reversed array (arr[0]toarr[d-1]) are reversed. - Finally, the remaining
n-delements (arr[d]toarr[n-1]) are reversed. This sequence of reversals correctly performs a right rotation.
Conclusion
Array rotation is a foundational operation with various applications in computer science and programming. We've explored several C programming approaches for both left and right rotations. While the 'one-by-one' method is intuitive for beginners, the 'temporary array' and 'reversal algorithm' generally offer more efficient solutions in terms of time complexity, especially for larger arrays and significant rotation counts. The reversal algorithm is particularly noteworthy for its O(N) time complexity and O(1) auxiliary space complexity.
Summary
Here are the key takeaways from this article:
- Array Rotation: Shifting elements of an array by a specified number of positions, either to the left or to the right.
- Left Rotation: Elements move towards the beginning of the array, and elements shifted out from the beginning wrap around to the end.
- Right Rotation: Elements move towards the end of the array, and elements shifted out from the end wrap around to the beginning.
- Methods Explored for Both Directions:
- One by One: Simple to implement but less efficient (O(N\*D) time complexity).
- Temporary Array: More efficient than one-by-one (O(N) time, O(D) space complexity).
- Reversal Algorithm: Often the most efficient in-place method (O(N) time, O(1) auxiliary space complexity).
- Prerequisites: Basic C knowledge, including arrays and functions, is essential.
- Use Cases: Image processing, cryptography, circular buffers, and various algorithmic optimizations.
Test Your Knowledge
- What is the main advantage of the reversal algorithm over the temporary array approach for array rotation?
- If an array
[Z, Y, X, W]is right-rotated by 1 position, what is the resulting array? - Describe a real-world scenario where a left array rotation might be more appropriate than a right rotation.
Challenge yourself: Explore and implement the Juggling Algorithm (GCD-based) for array rotation, which offers another efficient in-place solution!