fork download
  1. #include <stdio.h>
  2.  
  3. int binarySearch(int array[], int x, int low, int high) {
  4. while (low <= high) {
  5. int mid = low + (high - low) / 2;
  6.  
  7. if (array[mid] == x)
  8. return mid;
  9.  
  10. if (array[mid] < x)
  11. low = mid + 1;
  12.  
  13. else
  14. high = mid - 1;
  15. }
  16.  
  17. return -1;
  18. }
  19.  
  20. int main(void) {
  21. int array[] = {3, 4, 5, 6, 7, 8, 9};
  22. int n = sizeof(array) / sizeof(array[0]);
  23. int x = 4;
  24. int result = binarySearch(array, x, 0, n - 1);
  25. if (result == -1)
  26. printf("Not found");
  27. else
  28. printf("Element is found at index %d", result);
  29. return 0;
  30. }
Success #stdin #stdout 0s 5488KB
stdin
Standard input is empty
stdout
Element is found at index 1