-
Notifications
You must be signed in to change notification settings - Fork 4
/
rotation.py
76 lines (66 loc) · 1.82 KB
/
rotation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
# Time complexity: O(n)
# Juggling algorithm: https://www.geeksforgeeks.org/array-rotation/
def left_rotate_v1(arr, d):
n = len(arr)
g = gcd(n, d)
for i in xrange(0, g):
temp = arr[i]
j = i
while True:
k = j + d
if k >= n:
k = k - n
if k == i:
break
arr[j] = arr[k]
j = k
arr[j] = temp
# Time complexity: O(n)
# Reversal algorithm: https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
def left_rotate_v2(arr, d):
"""
Algorithm -
For arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 and n = 7
A = [1, 2] and B = [3, 4, 5, 6, 7]
Reverse A, we get ArB = [2, 1, 3, 4, 5, 6, 7]
Reverse B, we get ArBr = [2, 1, 7, 6, 5, 4, 3]
Reverse all, we get (ArBr)r = [3, 4, 5, 6, 7, 1, 2]
:param arr:
:param d:
:return:
"""
n = len(arr)
from reverse import reverse_arr
reverse_arr(arr, 0, d-1)
reverse_arr(arr, d, n-1)
reverse_arr(arr, 0, n-1)
# Time complexity: O(nd)
# Rotate one-by-one: https://www.geeksforgeeks.org/array-rotation/
def left_rotate_v3(arr, d):
from Array import swap
n = len(arr)
for di in xrange(0, d):
first = arr[0]
for i in xrange(1, n):
swap(arr, i, i-1)
arr[n-1] = first
if __name__ == "__main__":
from copy import deepcopy
d = 2
arr = [1, 2, 3, 4, 5, 6, 7]
arr_dup1 = deepcopy(arr)
arr_dup2 = deepcopy(arr)
print arr
print "\n---- Using V1 ----\n"
left_rotate_v1(arr, d)
print arr
print "\n---- Using V2 ----\n"
left_rotate_v2(arr_dup1, d)
print arr_dup1
print "\n---- Using V3 ----\n"
left_rotate_v3(arr_dup2, d)
print arr_dup2