Advertisement
R3v3rs3r

Binary search [C++]

Jan 18th, 2024
847
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.69 KB | Source Code | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int binSearch(int arr[], int l, int r, int x) {
  5.     while (l <= r) {
  6.         int m = l + (r - l) / 2;
  7.         if (arr[m] == x)
  8.         {
  9.             return m;
  10.         }
  11.         if (arr[m] < x) {
  12.             l = m + 1;
  13.         } else {
  14.             r = m - 1;
  15.         }    
  16.     }
  17.     return false;
  18. }
  19.  
  20. int main() {
  21.     int arr[10], x, res;
  22.     cout<<"Enter array elements: "<<endl;
  23.     for (int i=0; i<10; i++) {
  24.         cin>>arr[i];
  25.     }
  26.     cout<<"\nEnter element to search: ", cin>>x;
  27.     if (res=binSearch(arr, 0, 9, x), res) {
  28.         cout<<"\nElement found at index: "<<res;
  29.     } else {
  30.         cout<<"\nElement not found!";
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement