C语言数组旋转的反转算法程序
算法是一组按顺序执行的指令,用于解决给定的问题。在这里,我们将讨论数组旋转的反转算法,并为反转算法创建一个程序。
现在,让我们了解一些解决此问题所需的术语 -
数组 - 存储相同数据类型元素的容器。数组的大小(元素数量)在数组声明时固定。
数组旋转 - 旋转数组是更改数组元素的顺序。将元素的索引增加 1,并将最后一个元素的索引更改为 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 :
"); 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("
The left reversed array by %d elements is:
",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
广告