Code Binary Search
Code Binary Search
Send Feedback
Code Binary Search
The first line contains an Integer 'N', which denotes the size of the array/list.
The second line contains 'N' single space-separated integers representing the elements in the array/list.
The third line contains the value of X to be searched for in the array/list.
Print the index at which X is present for each test case, -1 otherwise.
0 <= N <= 10^6
0 <= X <= 10^9
Time Limit: 1 sec
7
1 3 7 9 11 12 45
3
1
7
1 2 3 4 5 6 7
9
-1
int binarySearch(int *input, int n, int val){ //Write your code here int start=0,end=n-1; while(end>=start){ int mid=start+(end-start)/2; if(input[mid]==val)return mid; else if(input[mid]>val)end=mid-1; else start=mid+1; } return -1;}
#include <iostream>using namespace std;
int binarySearch(int *input, int n, int val){ //Write your code here int start=0,end=n-1; while(end>=start){ int mid=start+(end-start)/2; if(input[mid]==val)return mid; else if(input[mid]>val)end=mid-1; else start=mid+1; } return -1;}
int main(){
// freopen("./Testcases/large/in/input10.txt", "r", stdin); // freopen("./Testcases/large/out/output10.txt", "w", stdout);
int size; cin >> size; int *input = new int[size];
for (int i = 0; i < size; ++i) { cin >> input[i]; }
int t = 1; // cin >> t;
while (t--) { int val; cin >> val; cout << binarySearch(input, size, val) << endl; }
delete [] input; return 0;}
Comments
Post a Comment