fork(2) download
  1. /*
  2. Description: Using Binary Strategy to Search in an array
  3.  
  4. in case of array elements are in increasing order.
  5. that means a[i]<=a[j] whenever i < j
  6.  
  7. Author: Liutong Xu
  8. Date: 2016/10/26
  9. */
  10.  
  11. #include <stdio.h>
  12. #define LIMIT 10
  13. int main()
  14. {
  15. int a[LIMIT] = {1,23,42,54,58,80,101,201,234,333};
  16. int i;
  17. int bottom = 0,top = LIMIT;
  18. int number;
  19.  
  20. printf("Please input a number to search: ");
  21. scanf("%d",&number);
  22. i = (bottom + top) / 2;
  23. while (number != a[i] && bottom < top)
  24. {
  25. if (number > a[i])
  26. bottom = i + 1;
  27. else
  28. top = i - 1;
  29. i = (bottom + top) / 2;
  30. }
  31. if (number == a[i])
  32. printf("a[%d] = %d!\n",i,number);
  33. else
  34. printf("The number %d is in not in the array!\n",number);
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 9432KB
stdin
42
stdout
Please input a number to search: a[2] = 42!