fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. static const int SIZE = 10;
  5.  
  6. int search(int arr[], int target, int startIndex, int endIndex)
  7. {
  8. if (startIndex > endIndex) return -1;
  9.  
  10. int midIndex = (startIndex + endIndex) / 2;
  11.  
  12. if (target == arr[midIndex])
  13. return midIndex;
  14. else if (target < arr[midIndex])
  15. search(arr, target, startIndex, midIndex-1);
  16. else
  17. search(arr, target, midIndex+1, endIndex);
  18. }
  19.  
  20. int main() {
  21. int arr[SIZE] = {1,2,3,4,5,6,7,8,9,10};
  22.  
  23. cout << "3 is at index: " << search(arr, 3, 0, SIZE-1) << endl;
  24. // cout << "11 is at index: " << search(arr, 11, 0 , SIZE-1) << endl;
  25.  
  26. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
3 is at index: 2