Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. // C++  Binary Search
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int binarySearch(int arr[], int start, int end, int x)
  6. {
  7.     while (start <= end) {
  8.         int m = start + (end - start) / 2;
  9.        
  10.         // Check if x is present at mid
  11.         if (arr[m] == x)
  12.             return m;
  13.  
  14.         // If x greater, ignore left half
  15.         if (arr[m] < x)
  16.             start = m + 1;
  17.  
  18.         // If x is smaller, ignore right half
  19.         else
  20.             end = m - 1;
  21.     }
  22.     return -1;
  23. }
  24.  
  25. int main(void)
  26. {
  27.     int arr[] = { 2, 3, 4, 10, 40 };
  28.     int x = 40;
  29.     int end = 5;
  30.  
  31.     int result = binarySearch(arr, 0, end - 1, x);
  32.    
  33.     if(result == -1)
  34.         cout << "Element is not present in array";
  35.     else
  36.         cout << "Element is present at index " << result;
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement