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