fork download
  1. /*
  2.   Copyright 2011 Marek "p2004a" Rusinowski
  3.   Binary search
  4. */
  5. #include <cstdio>
  6.  
  7. #define MAXN 1000000
  8.  
  9. int array[MAXN];
  10.  
  11. int pos(int *begin, int *end, int a) {
  12. int *old_begin = begin, *center = NULL;
  13. while (begin + 1 < end) {
  14. center = (end - begin) / 2 + begin;
  15. if (*center < a) {
  16. begin = center;
  17. } else if (*center > a) {
  18. end = center;
  19. } else {
  20. return center - old_begin;
  21. }
  22. }
  23. return begin - old_begin;
  24. }
  25.  
  26. int main() {
  27. int n, a;
  28. scanf("%d", &n);
  29. for (int i = 0; i < n; ++i) {
  30. scanf("%d", &array[i]);
  31. }
  32. scanf("%d", &a);
  33. printf("%d\n", pos(array, array + n, a) + 1);
  34. return 0;
  35. }
  36.  
stdin
15
-20 -15 -1 0 1 7 8 15 20 21 30 100 2000 100000 9999999
25
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:28: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
prog.cpp:30: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
prog.cpp:32: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
stdout
10