使用C++编写的数组旋转的逆转算法

使用C++编写的数组旋转的逆转算法

在给定的问题中,我们有一个数组,并且我们需要使用反转算法将数组旋转d个元素,例如 −

Input : arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] Explanation : As you can see we have to rotate this array by d = 2 but our main task is to achieve this by using a reversal technique.登录后复制

  • 首先,我们反转数组的前d个元素。
  • 其次,我们反转剩下的元素。
  • 第三,我们反转整个数组。

通过应用这三个步骤,我们可以得到旋转后的数组。

解决方案的方法

在这个问题中,首先,我们要编写一个反转元素的函数;现在我们按照上述步骤进行操作。

示例

#include using namespace std; void reverseArray(int arr[], int start, int end) { // our reversal algorithm while (start < end) { // if start becomes equal to end we break the loop int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return ; } void Rotate(int arr[], int d, int n) { // rotation function if (d == 0) // no rotation required return; d = d % n; // when d becomes equal to n so our array comes to its original form reverseArray(arr, 0, d - 1); // reversing first d elements reverseArray(arr, d, n - 1); // reversing the remaining elements reverseArray(arr, 0, n - 1); // reversing the whole array return ; } int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; // given array int n = sizeof(arr) / sizeof(arr[0]); // size of our array int d = 2; Rotate(arr, d, n); for(int i = 0; i < n; i++) // printing the array cout