Skip to content

Commit 00980ce

Browse files
committed
Solution to find the Floor of a Number in an Array
1 parent ef69033 commit 00980ce

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

‎src/BinaySearch/Ceiling.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ static int ceilingOfANumber(int[] array, int target){
1212
int startIndex = 0;
1313
int endIndex = array.length -1;
1414

15+
//This is to handle the case where the target is greater than the last index of the array.
16+
if (target > array[endIndex]){
17+
return -1;
18+
}
19+
1520
while(startIndex <= endIndex){
1621
//Find Middle Element
1722
int middle = (startIndex+endIndex)/2;

‎src/BinaySearch/Floor.java‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package BinaySearch;
2+
3+
// Ceiling:- The Smallest Element in an Array which is greater than or equal to the target
4+
public class Floor {
5+
public static void main(String[] args) {
6+
int[] array = {1,2,3,4,5,6,77,88,99,102,105,115,167};
7+
int answer = floorOfANumber(array,0);
8+
System.out.println(answer);
9+
}
10+
11+
static int floorOfANumber(int[] array, int target){
12+
int startIndex = 0;
13+
int endIndex = array.length -1;
14+
15+
//This is to handle the case where the target is greater than the last index of the array.
16+
if (target < array[startIndex]){
17+
return -1;
18+
}
19+
20+
while(startIndex <= endIndex){
21+
//Find Middle Element
22+
int middle = (startIndex+endIndex)/2;
23+
if (target == array[middle]){
24+
return array[middle];
25+
}else {
26+
if (target > array[middle]){
27+
startIndex = middle+1;
28+
System.out.println("Start Index Incremented");
29+
}else{
30+
endIndex = middle-1;
31+
System.out.println("End Index Decremented");
32+
}
33+
}
34+
}
35+
36+
return array[endIndex];
37+
}
38+
}

0 commit comments

Comments
 (0)