-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayUtils.java
100 lines (89 loc) · 2.58 KB
/
ArrayUtils.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
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
package iensen;
import java.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.
*/
public class ArrayUtils
{
public static void shuffle(Object[] a) {
int n = a.length;
Random random = new Random();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(Object[] a, int i, int changeIdx) {
Object temp = a[i];
a[i] = a[changeIdx];
a[changeIdx] = temp;
}
public static int lower_bound(Comparable[] arr, Comparable key) {
int len = arr.length;
int lo = 0;
int hi = len-1;
int mid = (lo + hi)/2;
while (true) {
int cmp = arr[mid].compareTo(key);
if (cmp == 0 || cmp > 0) {
hi = mid-1;
if (hi < lo)
return mid;
} else {
lo = mid+1;
if (hi < lo)
return mid<len-1?mid+1:-1;
}
mid = (lo + hi)/2;
}
}
public static int upper_bound(Comparable[] arr, Comparable key) {
int len = arr.length;
int lo = 0;
int hi = len-1;
int mid = (lo + hi)/2;
while (true) {
int cmp = arr[mid].compareTo(key);
if (cmp == 0 || cmp < 0) {
lo = mid+1;
if (hi < lo)
return mid<len-1?mid+1:-1;
} else {
hi = mid-1;
if (hi < lo)
return mid;
}
mid = (lo + hi)/2;
}
}
public static void reverse(int []a)
{
for(int i = 0; i < a.length/2; i++)
{
int temp = a[i];
a[i] = a[a.length - i - 1];
a[a.length - i - 1] = temp;
}
}
boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = 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;
}
return true;
}
return false;
}
}