Advertisement
shawonrog

binary search

Jun 3rd, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 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. j=1;
  35. break;
  36. }
  37.  
  38.  
  39. }
  40. if(low>high)
  41. {
  42. printf("number not found");
  43. }
  44. return mid;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement