Python Program for Reversal algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this article, we will explore the Reversal Algorithm for array rotation and implement it in Python.
Example
Input: arr[] = [1, 2, 3, 4, 5, 6, 7]
d = 2
Output: arr[] = [3, 4, 5, 6, 7, 1, 2]
Rotation of the above array by 2 will make an array
Python Program for Reversal Algorithm of Array Rotation
Python3
def rverseArray(arr,d):
c = (arr[d:]) + (arr[:d])
return c
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
d = 2
print (rverseArray(arr,d))
|
Output
[3, 4, 5, 6, 7, 1, 2]
Python Program for Reversal algorithm for Array Rotation
Python3
def rverseArray(arr, start, end):
while (start < end):
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start + = 1
end = end - 1
def leftRotate(arr, d):
n = len (arr)
rverseArray(arr, 0 , d - 1 )
rverseArray(arr, d, n - 1 )
rverseArray(arr, 0 , n - 1 )
def printArray(arr):
for i in range ( 0 , len (arr)):
print (arr[i])
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
leftRotate(arr, 2 )
printArray(arr)
|
Output
3
4
5
6
7
1
2
Last Updated :
28 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...