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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…