Advertisement
xBloodY

binary search

Jul 25th, 2022
806
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. int b_search(vector<int> a, int val) {
  6.     int l = 0, r = a.size() - 1;
  7.     while (r > l) {
  8.         int mid = (l + r) / 2;
  9.         if (a[mid] < val)
  10.             l = mid + 1;
  11.         else if (a[mid] > val)
  12.             r = mid - 1;
  13.         else
  14.             return mid;
  15.     }
  16.     return l;
  17. }
  18.  
  19. int main() {
  20.     vector<int> a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  21.     cout << b_search(a, 4);
  22.     return 0;
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement