fork download
  1.  
  2. //第3回 課題1
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. //この関数を実装する
  7. int binary_search(int a[],int n,int x){
  8.  
  9. int min = 0;
  10. int max = n - 1;
  11. int mid;
  12.  
  13. while (min <= max) {
  14. int mid = (min + max) / 2;
  15. if (a[mid] == x) {
  16. return mid;
  17. } else if(a[mid] < x){
  18. min = mid + 1;
  19. } else if(a[mid] > x){
  20. max = mid -1;
  21. }
  22. }
  23. }
  24.  
  25. int main(void) {
  26. int n,x,i;
  27. int *a;
  28. int ans = -1;
  29. scanf("%d %d",&n,&x);
  30. a = (int*)malloc(sizeof(int)*n);
  31. if(a==NULL){
  32. printf("ERROR\n");
  33. return -1;
  34. }
  35. for(i=0;i<n;i++){
  36. scanf("%d",&a[i]);
  37. }
  38. ans = binary_search(a,n,x);
  39. if(ans != -1) printf("a[%d] = %d\n",ans,a[ans]);
  40. else printf("not found\n");
  41. free(a);
  42. return 0;
  43. }
Success #stdin #stdout 0.01s 5284KB
stdin
12 5
1 2 3 5 27 4 767 435 45 32 45 32
stdout
a[11] = 0