forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArrayRotate.java
More file actions
70 lines (63 loc) · 1.96 KB
/
ArrayRotate.java
File metadata and controls
70 lines (63 loc) · 1.96 KB
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
package misc;
import java.util.*;
public class ArrayRotate {
public static void rotate1(int[] a, int first, int middle, int last) {
int next = middle;
while (first != next) {
swap(a, first++, next++);
if (next == last)
next = middle;
else if (first == middle)
middle = next;
}
}
public static void rotate2(int[] a, int first, int middle, int last) {
reverse(a, first, middle);
reverse(a, middle, last);
reverse(a, first, last);
}
static void reverse(int[] a, int from, int to) {
while (from + 1 < to) swap(a, from++, --to);
}
static void swap(int[] a, int i, int j) {
int t = a[j];
a[j] = a[i];
a[i] = t;
}
public static void rotate3(int[] a, int first, int middle, int last) {
int n = last - first;
int jump = middle - first;
for (int i = first, count = 0; count < n; i++) {
int cur = i;
int tmp = a[cur];
while (true) {
++count;
int next = cur + jump;
if (next >= last)
next -= n;
if (next == i)
break;
a[cur] = a[next];
cur = next;
}
a[cur] = tmp;
}
}
// random test
public static void main(String[] args) {
Random rnd = new Random(1);
for (int step = 0; step < 1000; step++) {
int n = rnd.nextInt(10) + 1;
int middle = rnd.nextInt(n);
int[] a = rnd.ints(n, 0, 10).toArray();
int[] b1 = a.clone();
rotate1(b1, 0, middle, n);
int[] b2 = a.clone();
rotate2(b2, 0, middle, n);
int[] b3 = a.clone();
rotate3(b3, 0, middle, n);
if (!Arrays.equals(b1, b2) || !Arrays.equals(b1, b3))
throw new RuntimeException();
}
}
}