Advertisement
Ritam_C

Binary_Search

Apr 22nd, 2021
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3. #define ull unsigned long long
  4. #define ld long double
  5. #define vi vector<int>
  6. #define vll vector<long long>
  7. #define pb push_back
  8. #define p_b pop_back
  9. using namespace std;
  10.  
  11. int Binary_Search(int arr[], int s, int e, int x){
  12.     if(e >= s){
  13.         int mid = s+(e-s)/2;
  14.         if(arr[mid] == x){
  15.             return mid;
  16.         } else if(arr[mid] > x){
  17.             return  Binary_Search(arr, s, mid-1, x);
  18.         } else{
  19.             return Binary_Search(arr, mid+1, e, x);
  20.         }
  21.     } else{
  22.         return -1;
  23.     }
  24. }
  25.  
  26. int main(){
  27.     ios_base::sync_with_stdio(false);
  28.     cin.tie(NULL);
  29.     int n; cin >> n;
  30.     int arr[n];
  31.     for(int i = 0; i < n; i++)  cin >> arr[i];
  32.     int key; cin >> key;
  33.     cout << Binary_Search(arr, 0, n-1, key) << "\n";
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement