C/C++ - 在不使用内置函数的情况下旋转数组的有效方法(作业)

ltw*_*ltw 3 c++ arrays algorithm performance

任务是向左旋转或向右旋转给定次数的阵列的子阵列.

让我以一个例子解释一下:

  • 让数据成为一个数组.

data = {0,1,2,3,4,5,6,7,8,9};

  • 子数组由参数begin和end确定.

如果开始= 3和结束= 7,则子阵列是{0,1,2,3,4,5,6,7, 8,9};

如果开始= 7和端= 3,则子阵列是{ 0,1,2,3,4,5,6,7,8,9 };

  • 让它旋转两次

如果开始= 3和结束= 7,则结果为{0,1,2,6,7,3,4,5, 8,9};

如果开始= 7和端= 3,则结果为{ 8,9,0,1, 4,5,6,2,3,7 };

我编写了执行此任务的代码,但速度很慢.有人能给我一个提示如何更快地提示吗?重要提示:我不允许使用除数据,子程序和内置函数之外的其他数组.

#include <iostream>
using namespace std;

int main(){

    int dataLength;

    cin >> dataLength;

    int data [ dataLength ];

    for (int i = 0; i < dataLength; i++){
        cin >> data [ i ];
    }


    int begin;
    int end;
    int rotation;
    int forLoopLength;
    int tempBefore;
    int tempAfter;

    cin >> begin;
    cin >> end;
    cin >> rotation;

    if (end > begin)
       forLoopLength = (end - begin) + 1;
    else
       forLoopLength = (end - begin) + 1 + dataLength;

    if (rotation < 0) 
       rotation = forLoopLength + (rotation % forLoopLength);
    else
        rotation = rotation % forLoopLength;

    for (int i = 0; i < rotation; i++) {

        tempBefore = data [ end ];

        for (int i = 0; i < forLoopLength; i++) {
            tempAfter = data [ (begin + i) % dataLength ];
            data [ (begin + i) % dataLength ] = tempBefore;
            tempBefore = tempAfter;
        }
    }

    for (int i = 0; i < dataLength; i ++ ) {
        cout << data [ i ] << " ";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ans 8

这有一个诀窍.如果在课堂上没有提到这个技巧,你就可以把它作为家庭作业,这很奇怪.无论如何...

要旋转M左边的N个元素序列:

  • 颠倒整个序列
  • 反转最后的M个元素
  • 反转第一个NM元素

DONE

例如,离开2:1234567 - > 7654321 - > 7654312 - > 3456712