193030

Binary Search

Feb 17th, 2020
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. // C++ program to implement recursive Binary Search
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // A iterative binary search function. It returns
  6. // location of x in given array arr[l..r] if present,
  7. // otherwise -1
  8. int binarySearch(int arr[], int l, int r, int x)
  9. {
  10.     while (l <= r) {
  11.         int m = l + (r - l) / 2;
  12.  
  13.         // Check if x is present at mid
  14.         if (arr[m] == x)
  15.             return m;
  16.  
  17.         // If x greater, ignore left half
  18.         if (arr[m] < x)
  19.             l = m + 1;
  20.  
  21.         // If x is smaller, ignore right half
  22.         else
  23.             r = m - 1;
  24.     }
  25.  
  26.     // if we reach here, then element was
  27.     // not present
  28.     return -1;
  29. }
  30.  
  31. int main(void)
  32. {
  33.     int arr[] = { 2, 3, 4, 10, 40 };
  34.     int x = 10;
  35.     int n = sizeof(arr) / sizeof(arr[0]);
  36.     int result = binarySearch(arr, 0, n - 1, x);
  37.     (result == -1) ? cout << "Element is not present in array"
  38.                    : cout << "Element is present at index " << result;
  39.     return 0;
  40. }
Add Comment
Please, Sign In to add comment