public
class
BinarySearchEqualOrClose {
private
static
void
printResult(
int
key,
int
pos,
SC sC)
{
System.out.println(
""
+ key +
", "
+ sC +
":"
+ pos);
}
enum
SC {
EQUAL,
EQUAL_OR_BIGGER,
EQUAL_OR_SMALLER
};
public
static
int
searchEqualOrClose(
int
key,
int
[] arr, SC sC)
{
if
(arr ==
null
|| arr.length ==
0
) {
return
-
1
;
}
if
(arr.length ==
1
) {
if
(arr[
0
] == key) {
return
0
;
}
if
(arr[
0
] < key && sC == SC.EQUAL_OR_SMALLER) {
return
0
;
}
if
(arr[
0
] > key && sC == SC.EQUAL_OR_BIGGER) {
return
0
;
}
return
-
1
;
}
return
searchEqualOrClose(arr, key,
0
, arr.length -
1
, sC);
}
private
static
int
searchEqualOrClose(
int
[] arr,
int
key,
int
start,
int
end, SC sC)
{
int
midPos = (start + end) /
2
;
int
midVal = arr[midPos];
if
(midVal == key) {
return
midPos;
}
if
(start >= end -
1
) {
if
(arr[end] == key) {
return
end;
}
if
(sC == SC.EQUAL_OR_SMALLER) {
if
(arr[start] > key && start !=
0
) {
return
start -
1
;
}
if
(arr[end] < key) {
return
end;
}
if
(arr[start] < key) {
return
start;
}
return
-
1
;
}
if
(sC == SC.EQUAL_OR_BIGGER) {
if
(arr[end] < key && end != arr.length -
1
) {
return
end +
1
;
}
if
(arr[start] > key) {
return
start;
}
if
(arr[end] > key) {
return
end;
}
return
-
1
;
}
return
-
1
;
}
if
(midVal > key) {
return
searchEqualOrClose(arr, key, start, midPos -
1
, sC);
}
return
searchEqualOrClose(arr, key, midPos +
1
, end, sC);
}
public
static
void
main(String[] args)
{
int
[] arr =
new
int
[] {
0
,
2
,
4
,
6
};
for
(
int
x = -
1
; x <=
7
; x++) {
int
pos = searchEqualOrClose(x, arr, SC.EQUAL);
printResult(x, pos, SC.EQUAL);
pos = searchEqualOrClose(x, arr, SC.EQUAL_OR_SMALLER);
printResult(x, pos, SC.EQUAL_OR_SMALLER);
pos = searchEqualOrClose(x, arr, SC.EQUAL_OR_BIGGER);
printResult(x, pos, SC.EQUAL_OR_BIGGER);
}
}
}