- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayUtils.java
More file actions
Latest commit
100 lines (89 loc) · 2.58 KB
/
Copy pathArrayUtils.java
File metadata and controls
100 lines (89 loc) · 2.58 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
packageiensen;
importjava.util.Random;
/**
* Created with IntelliJ IDEA.
* User: iensen
* Date: 2/24/13
* Time: 10:15 AM
* To change this template use File | Settings | File Templates.
*/
publicclassArrayUtils
{
publicstaticvoidshuffle(Object[] a) {
intn = a.length;
Randomrandom = newRandom();
for (inti = 0; i < n; i++) {
intchange = i + random.nextInt(n - i);
swap(a, i, change);
}
}
privatestaticvoidswap(Object[] a, inti, intchangeIdx) {
Objecttemp = a[i];
a[i] = a[changeIdx];
a[changeIdx] = temp;
}
publicstaticintlower_bound(Comparable[] arr, Comparablekey) {
intlen = arr.length;
intlo = 0;
inthi = len-1;
intmid = (lo + hi)/2;
while (true) {
intcmp = arr[mid].compareTo(key);
if (cmp == 0 || cmp > 0) {
hi = mid-1;
if (hi < lo)
returnmid;
} else {
lo = mid+1;
if (hi < lo)
returnmid<len-1?mid+1:-1;
}
mid = (lo + hi)/2;
}
}
publicstaticintupper_bound(Comparable[] arr, Comparablekey) {
intlen = arr.length;
intlo = 0;
inthi = len-1;
intmid = (lo + hi)/2;
while (true) {
intcmp = arr[mid].compareTo(key);
if (cmp == 0 || cmp < 0) {
lo = mid+1;
if (hi < lo)
returnmid<len-1?mid+1:-1;
} else {
hi = mid-1;
if (hi < lo)
returnmid;
}
mid = (lo + hi)/2;
}
}
publicstaticvoidreverse(int []a)
{
for(inti = 0; i < a.length/2; i++)
{
inttemp = a[i];
a[i] = a[a.length - i - 1];
a[a.length - i - 1] = temp;
}
}
booleannext_permutation(int[] p) {
for (inta = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (intb = p.length - 1;; --b)
if (p[b] > p[a]) {
intt = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
returntrue;
}
returnfalse;
}
}