Python Program for Reversal algorithm for array rotation

This article will teach you, how to use the Reversal algorithm for array using the python program.


Example

arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]

Rotated by k = 3    =========>   arr = [ 6, 7, 8, 1, 2, 3, 4, 5 ]


Explanation

  1. First we reverse the whole array.
  2. Now, we reverse the k element.
  3. And then finally, reverse the remaining element.
  4. And then we print the new array.


Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Reveral in array using python

# reverse the element 
def reverse(arr, start, end):
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1
        
# rotation
def rotation(arr,k):
    n = len(arr)

    reverse(arr, 0, n-1)  # Reverse the whole array
    reverse(arr, 0, k-1)  # Reverse the k element 
    reverse(arr, k, n-1)  # Reverse the remaning array
    return arr

# array
arr = [1,2,3,4,5,6,7,8]
k = 3
print(rotation(arr,k))


Output

[6, 7, 8, 1, 2, 3, 4, 5]
Next Post Previous Post
No Comment
Add Comment
comment url