企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 数组旋转程序 > 原文: [https://www.geeksforgeeks.org/array-rotation/](https://www.geeksforgeeks.org/array-rotation/) 编写一个函数`turn(ar[], d, n)`,该函数将大小为`n`的`arr[]`旋转`d`个元素。 ![Array](https://img.kancloud.cn/ad/82/ad82048d4bf6f0a8c770bcfbad1f7d5d_369x102.png "Array") 将上面的数组旋转 2 将使数组 ![ArrayRotation1](https://img.kancloud.cn/89/48/8948b7758e3a9610abc2ae2b8893978a_349x90.png "ArrayRotation1") **方法 1(使用临时数组)** ``` Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7 1) Store the first d elements in a temp array temp[] = [1, 2] 2) Shift rest of the arr[] arr[] = [3, 4, 5, 6, 7, 6, 7] 3) Store back the d elements arr[] = [3, 4, 5, 6, 7, 1, 2] ``` **时间复杂度**: `O(n)` **辅助空间**: `O(d)` **方法 2(一轮旋转)** ``` leftRotate(arr[], d, n) start For i = 0 to i < d Left rotate all elements of arr[] by one end ``` 要旋转一个,将`arr[0]`存储在临时变量`temp`中,将`arr[1]`移至`arr[0]`,将`arr[2]`移至`arr[1]`…最后将`temp`移至`arr[n-1]` 让我们以相同的示例`arr[] = [1,2,3,4,5,6,7]`,`d = 2`。将`arr []`旋转 2 次,我们得到`[2, 3]`,第一次旋转后为`[4, 5, 6, 7, 1]`,第二次旋转后为`[3, 4, 5, 6, 7, 1, 2]`。 下面是上述方法的实现: ## C++ ```cpp // C++ program to rotate an array by // d elements #include <bits/stdc++.h> using namespace std; /*Function to left Rotate arr[] of    size n by 1*/ void leftRotatebyOne(int arr[], int n) {     int temp = arr[0], i;     for (i = 0; i < n - 1; i++)         arr[i] = arr[i + 1];     arr[i] = temp; } /*Function to left rotate arr[] of size n by d*/ void leftRotate(int arr[], int d, int n) {     for (int i = 0; i < d; i++)         leftRotatebyOne(arr, n); } /* utility function to print an array */ void printArray(int arr[], int n) {     for (int i = 0; i < n; 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]);     // Function calling     leftRotate(arr, 2, n);     printArray(arr, n);     return 0; } ```