fork download
  1. #include <stdio.h>
  2. #define SIZE 15
  3.  
  4. int binarySearch(const int b[], int searchKey, size_t low, size_t high);
  5.  
  6. int main(void) {
  7. int a[SIZE];
  8.  
  9. for (size_t i = 0; i < SIZE; ++i) {
  10. a[i] = 2 * i;
  11. }
  12.  
  13. int key = 10;
  14. int result = binarySearch(a, key, 0, SIZE - 1);
  15.  
  16. if (result != -1) {
  17. printf("Found value at index %d\n", result);
  18. } else {
  19. printf("Value not found\n");
  20. }
  21.  
  22. return 0;
  23. }
  24.  
  25. int binarySearch(const int b[], int searchKey, size_t low, size_t high) {
  26. if (low > high) {
  27. return -1;
  28. }
  29.  
  30. size_t middle = (low + high) / 2;
  31.  
  32. if (searchKey == b[middle]) {
  33. return middle;
  34. } else if (searchKey < b[middle]) {
  35. if (middle == 0) {
  36. return -1;
  37. }
  38. return binarySearch(b, searchKey, low, middle - 1);
  39. } else {
  40. return binarySearch(b, searchKey, middle + 1, high);
  41. }
  42. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Found value at index 5