fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int binary_search(int a[],int n,int x){
  5. int lef=0;
  6. int rig=n-1;
  7. while(lef<=rig){
  8. int mid=(lef+rig)/2;
  9. if(a[mid]==x){ return mid; }
  10. else if(x<a[mid]){ rig=mid-1; }
  11. else if(x>a[mid]){ lef=mid+1; }
  12. }
  13. return -1;
  14. }
  15.  
  16. int main(void) {
  17. int n,x,i;
  18. int *a;
  19. int ans = -1;
  20. scanf("%d %d",&n,&x);
  21. a = (int*)malloc(sizeof(int)*n);
  22. if(a==NULL){
  23. printf("ERROR\n");
  24. return -1;
  25. }
  26. for(i=0;i<n;i++){
  27. scanf("%d",&a[i]);
  28. }
  29. ans = binary_search(a,n,x);
  30. if(ans != -1) printf("a[%d] = %d\n",ans,a[ans]);
  31. else printf("not found\n");
  32. free(a);
  33. return 0;
  34. }
  35.  
Success #stdin #stdout 0s 5268KB
stdin
12 9
1 2 3 4 5 8 9 13 16 21 25 27
stdout
a[6] = 9