peshopbs2

Binary search on 1d array. The input should be sorted in asc

Jul 31st, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5.     int n, k, arr[1000000];
  6.     cin >> n;
  7.     for(int i = 0; i < n; i++) cin >> arr[i];
  8.     cin >> k;
  9.     int l = 0, r = n-1, mid, pos = -1;
  10.    
  11.     while(l<=r) {
  12.         mid = (l+r) / 2;
  13.         if(arr[mid]>k) {
  14.             r = mid-1;
  15.         } else if(arr[mid]<k) {
  16.             l = mid+1;
  17.         } else {
  18.             pos = mid;
  19.             break;
  20.         }
  21.     }
  22.  
  23.     if(pos!=-1) {
  24.         cout << "Found at index: " << pos << endl;
  25.     } else {
  26.         cout << "Not found" << endl;
  27.     }
  28.    
  29.     return 0;
  30. }
Add Comment
Please, Sign In to add comment