Adrita

binary search iterative ( ds lab 1) 3rd sem

Jan 7th, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. #include<stdio.h>
  2. int main()
  3. {
  4. int a,ar[100],i,n;
  5. for(i=0;;i++)
  6. {
  7. scanf("%d",&a);
  8. if(a>=0)
  9. ar[i]=a;
  10. else
  11. break;
  12. }
  13. scanf("%d",&n);
  14. int len,l,r,m;
  15. len=i;
  16. l=0,r=len-1,m=(l+r)/2;
  17. while(l<=r)
  18. {
  19. if(ar[m]==n)
  20. {
  21. printf("%d",m);
  22. return 0;
  23. }
  24. else
  25. {
  26. if(n>ar[m])
  27. l=m+1;
  28. else if(n<ar[m])
  29. r=m-1;
  30. }
  31. m=(l+r)/2;
  32. }
  33. if(l>r)
  34. printf("-1");
  35. }
Add Comment
Please, Sign In to add comment