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