ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 数组旋转的逆向算法 > 原文: [https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/](https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/) 编写一个函数`turn(arr[], d, n)`,该函数将大小为`n`的`arr[]`旋转`d`个元素。 **示例**: ``` Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] ``` ![Array](https://img.kancloud.cn/fa/6c/fa6cc3eac6c4dd01631156ab85b36e87_395x58.png "Array") 将上面的数组旋转 2 将使数组 ![ArrayRotation1](https://img.kancloud.cn/8e/2c/8e2cf17600f8a06167071fa55fde816f_395x52.png "ArrayRotation1") 在[这里](https://www.geeksforgeeks.org/array-rotation/)中讨论了通过`d`个元素旋转数组的前 3 种方法。 **方法 4(反向算法)**: **算法**: ``` rotate(arr[], d, n) reverse(arr[], 1, d) ; reverse(arr[], d + 1, n); reverse(arr[], 1, n); ``` 令`AB`为输入数组的两个部分,其中`A = arr[0..d-1]`和`B = arr[d..n-1]`。 该算法的思想是: * 反转`A`以获得`ArB`,其中`Ar`反转`A`。 * 反转`B`以获得`ArBr`,其中`Br`反转`B`. * 取反得到`(ArBr)r = BA`。 **示例**: 令数组为 `arr[] = [1, 2, 3, 4, 5, 6, 7]`,`d = 2`和`n = 7` `A = [1, 2]`和`B = [3, 4, 5, 6, 7]` * 反向`A`,我们得到`ArB = [2, 1, 3, 4, 5, 6, 7]` * 反向`B`,我们得到`ArBr = [2, 1, 7, 6, 6, 5, 4, 3]` * 反向所有,我们得到`(ArBr)r = [3, 4, 5, 6, 6, 7, 1, 2]` ` 下面是上述方法的实现: ## C++ ```cpp // C++ program for reversal algorithm // of array rotation #include <bits/stdc++.h> using namespace std; /*Function to reverse arr[] from index start to end*/ void rvereseArray(int arr[], int start, int end) {     while (start < end) {         int temp = arr[start];         arr[start] = arr[end];         arr[end] = temp;         start++;         end--;     } } /* Function to left rotate arr[] of size n by d */ void leftRotate(int arr[], int d, int n) {     if (d == 0)         return;     rvereseArray(arr, 0, d - 1);     rvereseArray(arr, d, n - 1);     rvereseArray(arr, 0, n - 1); } // Function to print an array void printArray(int arr[], int size) {     for (int i = 0; i < size; i++)         cout << arr[i] << " "; } /* Driver program to test above functions */ int main() {     int arr[] = { 1, 2, 3, 4, 5, 6, 7 };     int n = sizeof(arr) / sizeof(arr[0]);     int d = 2;     // in case the rotating factor is     // greater than array length     d = d % n;     // Function calling     leftRotate(arr, d, n);     printArray(arr, n);     return 0; } ```