/
BinarySearch.java
106 lines (83 loc) · 2.38 KB
/
BinarySearch.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
101
102
103
104
105
106
package com.bpeldi2oerkd8.lib;
public class BinarySearch {
//okの条件(ここを問題ごとに変える)(int)
public static boolean isOK(Integer[] a, int index, int key) {
if(a[index] >= key)
return true;
else
return false;
}
//okの条件(ここを問題ごとに変える)(long)
public static boolean isOK(Long[] a, int index, long key) {
if(a[index].longValue() >= key)
return true;
else
return false;
}
//めぐる式二分探索(デフォルトはkey以上を満たす最小のindexを返す)(int)
public static int binary_search(Integer[] a, int key, int ng, int ok) {
// int ng = -1;
// int ok = a.length;
if(ng < ok)
ng--;
else
ok--;
while(Math.abs(ok-ng) > 1) {
int mid = (ok+ng) / 2;
if(isOK(a, mid, key))
ok = mid;
else
ng = mid;
}
return ok;
}
//めぐる式二分探索(デフォルトはkey以上を満たす最小のindexを返す)(long)
public static int binary_search(Long[] a, long key, int ng, int ok) {
// int ng = -1;
// int ok = a.length;
if(ng < ok)
ng--;
else
ok--;
while(Math.abs(ok-ng) > 1) {
int mid = (ok+ng) / 2;
if(isOK(a, mid, key))
ok = mid;
else
ng = mid;
}
return ok;
}
//keyが含まれているか(int)
public static boolean containsValue(Integer[] a, int key) {
int index = binary_search(a, key, 0, a.length);
if(index < 0 || index >= a.length || a[index] != key)
return false;
else
return true;
}
//keyが含まれている個数(int)
public static int countValue(Integer[] a, int key) {
int index1 = binary_search(a, key, 0, a.length);
int index2 = binary_search(a, key+1, 0, a.length);
if(index1 < 0 || index1 >= a.length || a[index1] != key)
return 0;
return index2 - index1;
}
//keyが含まれているか(long)
public static boolean containsValue(Long[] a, long key) {
int index = binary_search(a, key, 0, a.length);
if(index < 0 || index >= a.length || a[index] != key)
return false;
else
return true;
}
//keyが含まれている個数(long)
public static int countValue(Long[] a, long key) {
int index1 = binary_search(a, key, 0, a.length);
int index2 = binary_search(a, key+1, 0, a.length);
if(index1 < 0 || index1 >= a.length || a[index1] != key)
return 0;
return index2 - index1;
}
}