-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloorandceil.java
52 lines (44 loc) · 1.32 KB
/
floorandceil.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
public class floorandceil {
static int findFloor(int[] arr, int n, int x) {
int low = 0, high = n - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] <= x) {
ans = arr[mid];
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
static int findCeil(int[] arr, int n, int x) {
int low = 0, high = n - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = arr[mid];
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
public static int[] getFloorAndCeil(int[] arr, int n, int x) {
int f = findFloor(arr, n, x);
int c = findCeil(arr, n, x);
return new int[] {f, c};
}
public static void main(String[] args) {
int[] arr = {3, 4, 4, 7, 8, 10};
int n = 6, x = 5;
int[] ans = getFloorAndCeil(arr, n, x);
System.out.println("The floor and ceil are: " + ans[0]
+ " and " + ans[1]);
}
}
//time complexity -O(log n)
//space complexity -O(1)