Advertisement
GlitchyTech

Untitled

Feb 28th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. using namespace std;
  5.  
  6. int main(){
  7.     int n = 0;
  8.     cout << "Size : ";
  9.     cin >> n;
  10.     int a[n] = {};
  11.     cout << "Elements : ";
  12.     for (int i = 0; i < n; ++i) cin >> a[i];
  13.     int key = 0;
  14.     cout << "Key : ";
  15.     cin >> key;
  16.    
  17.     sort(a, a + n);
  18.    
  19.     int l = -1;
  20.     int r = n;
  21.     while (l < r - 1){
  22.         int m = (l + r) / 2;
  23.         if (key > a[m]) l = m;
  24.         else r = m;
  25.     }
  26.    
  27.     if (a[r] == key) cout << "First element's index in sorted array : " << r;
  28.     else cout << "Array doesn't have such element";
  29.     return 0;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement