fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int binarySearch(int arr[], int l, int r, int x) {
  5. if (l <= r) {
  6. int mid = l + (r - l) / 2;
  7. if (arr[mid] == x) return mid;
  8. if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x);
  9. return binarySearch(arr, mid + 1, r, x);
  10. }
  11. return -1;
  12. }
  13.  
  14. int main() {
  15. int arr[] = {2, 4, 10, 20, 40};
  16. int n = sizeof(arr)/sizeof(arr[0]);
  17. int x = 10;
  18. int result = binarySearch(arr, 0, n - 1, x);
  19. if(result != -1)
  20. cout << "Element found at index " << result << endl;
  21. else
  22. cout << "Element not found" << endl;
  23. return 0;
  24. }
Success #stdin #stdout 0.02s 25416KB
stdin
Standard input is empty
stdout
#include <iostream>
using namespace std;

int binarySearch(int arr[], int l, int r, int x) {
    if (l <= r) {
        int mid = l + (r - l) / 2;
        if (arr[mid] == x) return mid;
        if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x);
        return binarySearch(arr, mid + 1, r, x);
    }
    return -1;
}

int main() {
    int arr[] = {2, 4, 10, 20, 40};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 10;
    int result = binarySearch(arr, 0, n - 1, x);
    if(result != -1)
        cout << "Element found at index " << result << endl;
    else
        cout << "Element not found" << endl;
    return 0;
}