-
Notifications
You must be signed in to change notification settings - Fork 72
/
binary_search
50 lines (46 loc) · 1 KB
/
binary_search
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
//Initial Template for C
#include <stdio.h>
#include <stdlib.h>
// } Driver Code Ends
//User function Template for C
// Function to find floor of K
// arr[]: integer array of size N
// N: size of arr[]
// K: element whose floor is to find
int findFloor(long long int arr[], int N, long long int K) {
int start=0;
int end=N-1;
int res=-1;
while(start<=end)
{
int mid=start+(end-start)/2;
if(arr[mid] <= K)
{
res=mid;
start=mid+1;
}
else if(arr[mid] >K){
end=mid-1;
}
}
return res;
}
// { Driver Code Starts.
int main() {
long long int t;
scanf("%lld", &t);
while(t--){
int n;
scanf("%d", &n);
long long int x;
scanf("%lld", &x);
long long int *arr;
arr = (long long int *)malloc(n * sizeof(long long int));
for(int i = 0;i<n;i++){
scanf("%lld", &arr[i]);
}
printf("%d\n", findFloor(arr, n, x) );
}
return 0;
}
// } Driver Code Ends