forked from the-moonLight0/Hactober-fest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayRotationBlockSwapAlgo.java
46 lines (40 loc) · 1.22 KB
/
ArrayRotationBlockSwapAlgo.java
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
public class ArrayRotationBlockSwapAlgo {
public static void leftRotate(int arr[], int d, int n) {
leftRotateRec(arr, 0, d, n);
}
public static void leftRotateRec(int arr[], int i, int d, int n) {
if (d == 0 || d == n)
return;
if (n - d == d) {
swap(arr, i, n - d + i, d);
return;
}
if (d < n - d) {
swap(arr, i, n - d + i, d);
leftRotateRec(arr, i, d, n - d);
} else /* If B is shorter*/ {
swap(arr, i, d, n - d);
leftRotateRec(arr, n - d + i, 2 * d - n, d); /*This is tricky*/
}
}
public static void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void swap(int arr[], int fi,
int si, int d) {
int i, temp;
for (i = 0; i < d; i++) {
temp = arr[fi + i];
arr[fi + i] = arr[si + i];
arr[si + i] = temp;
}
}
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
leftRotate(arr, 2, 7);
printArray(arr, 7);
}
}