-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloor.java
More file actions
37 lines (30 loc) · 862 Bytes
/
Copy pathFloor.java
File metadata and controls
37 lines (30 loc) · 862 Bytes
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
package com.binarySearch;
public class Floor {
public static void main(String[] args) {
int[] arr = {2, 3, 5, 9, 14, 16, 18};
int target = 18;
int ans = floor(arr, target);
System.out.println(ans);
}
// return the index of the target
static int floor(int [] arr, int target){
int start = 0;
int end = arr.length - 1;
// while start is not greater than end
while(start <= end){
// better way to find the mid
int mid = start + (end - start) / 2;
// target is greater than mid
if(target > arr[mid]){
start = mid + 1;
}
else if(target < arr[mid]){
end = mid - 1;
}
else{
return mid;
}
}
return end;
}
}