Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c++ - Right rotation operation

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.

question from:https://stackoverflow.com/questions/65839869/right-rotation-operation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...