数组旋转的逆向算法C程序
的算法是一组指令,以便解决给定问题进行。在这里,我们将讨论数组旋转的逆向算法,并为逆向算法创建程序。
现在,让我们来解决一些需要解决的问题-
数组-相同数据类型的元素的容器。声明数组时,数组的大小(元素数)是固定的。
数组旋转-旋转数组正在更改数组元素的顺序。将元素的索引增加一个,然后将最后一个元素的索引更改为0,依此类推。
数组旋转的例子,
Array[] = {3, 6, 8,1, 4, 10} Rotated 2 times gives, Array[] = {4, 10, 3, 6, 8, 1, 4}
逆向算法
数组旋转的算法之一是反转算法。在此算法中,创建子数组并将其反转以执行数组的旋转。创建子数组,将其单独旋转,然后连接在一起,然后反向反转以获得旋转后的数组。
算法
Input : array arr[] , positions that are needed to be rotated r , length of array n. Step 1: Split the array into two sub arrays of 0 - (d-1) and d - (n-1) size, a1 [d] and a2[n-d]; Step 2: Reverse both arrays using the reverse method. Step 3: Join a1 and a2 back to get an array of original size. Step 4: Reverse this joined array to get the rotated array. Step 5: Print the array using the standard output method.
例,
arr[] = {1 ,4, 2, 8, 3, 6, 5}, d = 3, n = 7 a1[] = {1,4,2} ; a2 = {8,3,6,5} a1r[] = {2,4,1} // reversed a1 a2r[] = {5,6,3,8} // reversed a2 ar[] = {2,4,1,5,6,3,8} // a1r+a2r arr[] = {8,3,6,5,1,4,2} // final answer.
示例
#include <stdio.h> void reverse(int arr[], int start, int end){ int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } int main(){ int arr[] = { 54, 67, 12, 76, 25, 16, 34 }; int n = 7; int d = 2; printf("The initial array is :\n"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); reverse(arr, 0, d - 1); reverse(arr, d, n - 1); reverse(arr, 0, n - 1); printf("\nThe left reversed array by %d elements is:\n",d); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0; }
输出结果
The initial array is : 54 67 12 76 25 16 34 The left reversed array by 2 elements is: 12 76 25 16 34 54 67