We had to write a program that would perform rotation of elements in an array. The array size was entered by user, so it had to be in a sense, dynamic.
Rotation or Circular Shifting
Initial Array: 1 3 7 4 8 6 5 2 9
Shift by: 4
Final Array: 6 5 2 9 1 3 7 4 8
Notice, in rotation, each elements position increased by shift amount. Also, elements in the end came to the front.
My Try
I used an approach in which I had to create a new array of size = shift amount. This array stored the shift no. of elements in the end of array. Now I shifted all the elements in the beginning of array by shift amount. In the end, I copied the elements of shift sized array to beginning of original array.
I tried to use minimum memory possible so only used shift sized array. I and keep it a bit fast (shift%=n statement to reduce inefficiency if shift >= n).
// Rotation
#include <iostream>
int main() {
int n;
std::cout << "Array size: ";
std::cin >> n;
int* list = new int[n];
std::cout << "Enter elements:\n";
for( int i = 0; i < n; ++i) {
std::cin >> list[i];
}
int shift;
std::cout << "Shift amount: ";
std::cin >> shift;
shift %= n; // to reduce work if shift > n
int* temp = new int[shift];
for( int i = n-shift; i < n ; ++i) {
temp[i-n+shift] = list[i];
}
for( int i = n-1; i >= shift; --i) {
list[i] = list[i-shift];
}
for( int i = 0; i < shift; ++i) {
list[i] = temp[i];
}
delete [] temp;
// Printing
for( int i = 0; i < n; ++i) {
std::cout << list[i] << " ";
}
delete [] list;
}
Question
My question is that all the optimization that i was able to make were a bit obvious and natural. I wanted to know if there was a significant algorithmic, or memory optimization possible for this problem.
PS
I know there's a function std::rotate
available from algorithm
, but we had to solve this problem on our own.