fork download
  1. #include <stdio.h>
  2.  
  3. #define ORIGINAL 0
  4. #define SOLUTION 1
  5.  
  6. int binsearch(int x, int v[], int n);
  7.  
  8.  
  9. int main(void){
  10. int i, n;
  11. unsigned int x = 0xFF30;
  12. int v[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  13.  
  14. /*for(i = 0; i <= 9; i++)
  15. printf("%d%4d\n", i, binsearch(i, v, 10));*/
  16. printf("%d%4d\n", 0, binsearch(0, v, 10));
  17. printf("%d%4d\n", 9, binsearch(9, v, 10));
  18. printf("%d%4d\n", 3, binsearch(3, v, 10));
  19. printf("%d%4d\n", 60, binsearch(60, v, 10));
  20. printf("%d%4d\n", -2, binsearch(-2, v, 10));
  21.  
  22. return 0;
  23. }
  24.  
  25. #if ORIGINAL
  26. /*Èñõîäíûé âàðèàíò áèíàðíîãî ïîèñêà*/
  27. int binsearch(int x, int v[], int n){
  28. int low, high, mid;
  29.  
  30. low = 0;
  31. high = n - 1;
  32. while(low <= high){
  33. mid = (low + high) / 2;
  34. if(x < v[mid])
  35. high = mid - 1;
  36. else if(x > v[mid])
  37. low = mid + 1;
  38. else
  39. return mid;
  40. }
  41. return - 1;
  42. }
  43. #endif
  44.  
  45. #if SOLUTION
  46. /*Ðåøåíèå çàäà÷è 3.1*/
  47. int binsearch(int x, int v[], int n){
  48. int low, high, mid;
  49.  
  50. low = 0;
  51. high = n - 1;
  52. while(low < high){
  53. mid = (low + high) / 2;
  54. if(x <= v[mid])
  55. high = mid;
  56. else
  57. low = mid + 1;
  58. printf("low = %d, high = %d\n", low, high);
  59. }
  60. if(v[high] == x && v[low] == x)
  61. return high;
  62. else
  63. return -1;
  64. }
  65. #endif
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
low = 0, high = 4
low = 0, high = 2
low = 0, high = 1
low = 0, high = 0
0   0
low = 5, high = 9
low = 8, high = 9
low = 9, high = 9
9   9
low = 0, high = 4
low = 3, high = 4
low = 3, high = 3
3   3
low = 5, high = 9
low = 8, high = 9
low = 9, high = 9
60  -1
low = 0, high = 4
low = 0, high = 2
low = 0, high = 1
low = 0, high = 0
-2  -1