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