-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloor in sorted array
More file actions
56 lines (48 loc) · 1.09 KB
/
Floor in sorted array
File metadata and controls
56 lines (48 loc) · 1.09 KB
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
53
54
55
56
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
//your code here
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int[] arr= new int[n];
int x= sc.nextInt();
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println(findFloor(arr,x));
}
public static int findFloor(int[] arr, int x){
if(arr[0]>x){
return -1;
}
int n = arr.length;
if(arr[n-1]<x){
return n-1;
}
int lo = 0;
int hi = n-1;
while(lo<=hi){
int mid = lo + (hi-lo)/2;
if(arr[mid]==x){
return mid;
}
else if(arr[mid]>x){
hi = mid-1;
}
else if(arr[mid]<x){
if(arr[mid+1]>x){
return mid;
}
else{
lo = mid+1;
}
}
}
return -1;
}
}