fork(1) download
  1. #include <stdio.h>
  2.  
  3. // Recursive implementation of Binary Search Algorithm to return
  4. // the position of target x in the sub-array A[low..high]
  5. int binarySearch(int A[], int low, int high, int x)
  6. {
  7. // Base condition (search space is exhausted)
  8. if (low > high)
  9. return -1;
  10.  
  11. // we find the mid value in the search space and
  12. // compares it with target value
  13.  
  14. int mid = (low + high)/2; // overflow can happen
  15. // int mid = low + (high - low)/2;
  16.  
  17. // Base condition (target value is found)
  18. if (x == A[mid])
  19. return mid;
  20.  
  21. // discard all elements in the right search space
  22. // including the mid element
  23. else if (x < A[mid])
  24. return binarySearch(A, low, mid - 1, x);
  25.  
  26. // discard all elements in the left search space
  27. // including the mid element
  28. else
  29. return binarySearch(A, mid + 1, high, x);
  30. }
  31.  
  32. // Recursive implementation of Binary Search Algorithm
  33. int main(void)
  34. {
  35. int A[] = { 2, 5, 6, 8, 9, 10 };
  36. int target = 5;
  37.  
  38. int n = sizeof(A)/sizeof(A[0]);
  39.  
  40. int low = 0, high = n - 1;
  41. int index = binarySearch(A, low, high, target);
  42.  
  43. if (index != -1)
  44. printf("Element found at index %d", index);
  45. else
  46. printf("Element not found in the array");
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
Element found at index 1