Advertisement
Saleh127

Untitled

May 2nd, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // A recursive binary search function. It returns
  5. // location of x in given array arr[l..r] is present,
  6. // otherwise -1
  7. int binarySearch(int arr[], int l, int r, int x)
  8. {
  9. if (r >= l) {
  10. int mid = l + (r - l) / 2;
  11.  
  12. // If the element is present at the middle
  13. // itself
  14. if (arr[mid] == x)
  15. return mid;
  16.  
  17. // If element is smaller than mid, then
  18. // it can only be present in left subarray
  19. if (arr[mid] > x)
  20. return binarySearch(arr, l, mid - 1, x);
  21.  
  22. // Else the element can only be present
  23. // in right subarray
  24. return binarySearch(arr, mid + 1, r, x);
  25. }
  26.  
  27. // We reach here when element is not
  28. // present in array
  29. return -1;
  30. }
  31.  
  32. int main(void)
  33. {
  34. int arr[] = { 2, 3, 4, 10, 40 };
  35. int x = 10;
  36. int n = sizeof(arr) / sizeof(arr[0]);
  37. int result = binarySearch(arr, 0, n - 1, x);
  38. (result == -1) ? cout << "Element is not present in array"
  39. : cout << "Element is present at index " << result;
  40. return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement