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