fork(1) download
  1. //第3回 課題1
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. //この関数を実装する
  6. int binary_search(int a[],int n,int x){
  7. //この関数の内側だけを書く
  8. int lef=0,rig=n-1,ans=-1;
  9. int mid;
  10. while(lef<=rig){
  11. mid=(lef+rig)/2;
  12. if(a[mid]==x){
  13. ans=mid;
  14. break;
  15. }else if(mid>x){
  16. rig=mid-1;
  17. }else{
  18. lef=mid+1;
  19. }
  20.  
  21. }
  22. return ans;
  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 0s 5512KB
stdin
10 5 1 2 3 4 5 6 7 8 9 10
stdout
a[4] = 5