Right rotation operation

Viewed 82
int main()
{
    int shiftSteps, newposition;
    int numbers[10], numberscopy[10];
    cin >> shiftSteps;

    for (int i = 0; i < 10; i++)
        cin >> numbers[i];

    for (int i = 0; i < 10; i++)
        numberscopy[i] = numbers[i];

    //----------------------------------------

    for (int i = 0; i < 10; i++)
    {
        newposition = (i + shiftSteps) % 10;
        numbers[newposition] = numberscopy[i];
    }

     for (int i = 0; i < 10; i++)
        cout << numbers[i] << "  ";
}

I wrote this code to rotate 10 numbers to Right with auxiliary array "numberscopy", but i want to rewrite the code without auxiliary array and i don't know how.

2 Answers

You can rotate the array in-place, i.e. without using an auxiliary array with std::rotate which is a standard algorithm.

std::rotate(numbers, numbers + shiftSteps, numbers + 10);

Without auxiliary array, you can make use of reversal algorithm to rotate array by "shiftSteps". It involves following three steps,

  • reversing array from 0 to sizeOfArray-1
  • reversing array from 0 to shiftSteps-1
  • reversing array from shiftSteps to sizeOfArray-1

Here's final code,

void reverseArray(int numbers[], int begin, int end) 
{ 
    while (begin < end) 
    { 
        swap(numbers[begin], numbers[end]); 
        begin++; 
        end--; 
    } 
} 

void rightRotate(int numbers[], int shiftSteps, int sizeOfArray) 
{ 
    reverseArray(numbers, 0, sizeOfArray-1);
    reverseArray(numbers, 0, shiftSteps-1);
    reverseArray(numbers, shiftSteps, sizeOfArray-1);
    
} 


int main()
{
    int shiftSteps;
    int numbers[10];
    cin >> shiftSteps;

    for (int i = 0; i < 10; i++)
        cin >> numbers[i];

    rightRotate(numbers, shiftSteps, 10);
 
    for (int i = 0; i < 10; i++)
        cout << numbers[i] << "  ";
}

Source for more info.

Related