Skip to content
This repository has been archived by the owner on Nov 3, 2024. It is now read-only.

Added C++ solution for Array Rotation using Reversal Algorithm #120

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions Beginner Level 📁/Array Rotation/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <iostream>
using namespace std;

// Function to reverse an array from index start to end
void reverseArray(int arr[], int start, int end) {
while (start < end) {
swap(arr[start], arr[end]);
start++;
end--;
}
}

// Function to rotate the array to the left by d positions using the reversal algorithm
void rotateArray(int arr[], int d, int n) {
// Step 1: Reverse the first 'd' elements
reverseArray(arr, 0, d-1);

// Step 2: Reverse the remaining 'n-d' elements
reverseArray(arr, d, n-1);

// Step 3: Reverse the entire array
reverseArray(arr, 0, n-1);
}

// Utility function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int n, d;
cout << "Enter the size of the array: ";
cin >> n;

int arr[n];
cout << "Enter array elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];

cout << "Enter the number of positions to rotate: ";
cin >> d;

// Rotate the array by 'd' positions
rotateArray(arr, d, n);

// Print the rotated array
cout << "Rotated array: ";
printArray(arr, n);

return 0;
}
5 changes: 4 additions & 1 deletion Beginner Level 📁/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@
"name": "Ramanpreet Kaur",
"githubUsername": "1998ramanpreet"
},

{
"name": "Sivendra B",
"githubUsername": "Astordnomer"
},
]