Skip to content

Commit 927d36b

Browse files
authored
Create Ceiling.java
This java program returns the ceiling of a given number in a sorted array
1 parent bb69473 commit 927d36b

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Ceiling.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
public class Ceiling {
2+
3+
public static void main(String[] args) {
4+
int[] arr = {2, 3, 5, 9, 14, 16, 18};
5+
int target = 15;
6+
int ans = ceiling(arr, target);
7+
System.out.println(ans);
8+
}
9+
10+
// return the index of smallest no >= target
11+
static int ceiling(int[] arr, int target) {
12+
13+
// but what if the target is greater than the greatest number in the array
14+
if (target > arr[arr.length - 1]) {
15+
return -1;
16+
}
17+
int start = 0;
18+
int end = arr.length - 1;
19+
20+
while(start <= end) {
21+
// find the middle element
22+
// int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java
23+
int mid = start + (end - start) / 2;
24+
25+
if (target < arr[mid]) {
26+
end = mid - 1;
27+
} else if (target > arr[mid]) {
28+
start = mid + 1;
29+
} else {
30+
// ans found
31+
return mid;
32+
}
33+
}
34+
return start;
35+
}
36+
}

0 commit comments

Comments
 (0)