shawonrog

binary search

Jun 2nd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main()
  5. {
  6. int low,high,mid,j,n,x;
  7. int a[10];
  8. printf("Enter how many numbers");
  9. scanf("%d",&n);
  10. for(j=0;j<n;j++)
  11. {
  12. scanf("%d",&a[j]);
  13. }
  14. printf("which number do you want");
  15. scanf("%d",&x);
  16. low=1;
  17. high=n;
  18.  
  19. while(low<=high)
  20. {
  21. mid=(low+high/2);
  22.  
  23. if(x<a[mid])
  24. {
  25. high=mid-1;
  26. }
  27. else if(x>a[mid])
  28. {
  29. low=mid+1;
  30. }
  31. else if(a[mid]==x)
  32. {
  33. printf("number found %d",mid);
  34. break;
  35. }
  36.  
  37.  
  38. }
  39. if(j==0)
  40. {
  41. printf("number not found");
  42. }
  43. return mid;
  44. }
Add Comment
Please, Sign In to add comment