Advertisement
edutedu

cautare binara recursiv

Feb 19th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. int n, a[100], x;
  5. int caut(int st, int dr)
  6. {
  7. int m;
  8. if(st==dr && a[st]==x)
  9. return st;
  10. if(st==dr && a[st]!=x)
  11. return 0;
  12. else
  13. {
  14. m=(st+dr)/2;
  15. if(x==a[m])
  16. return m;
  17. else if(x<a[m])
  18. caut(st, m-1);
  19. else
  20. caut(m+1, dr);
  21.  
  22. }
  23. }
  24. int main()
  25. {
  26. int i;
  27. cin>>n;
  28. cin>>x;
  29. for(i=1; i<=n; i++)
  30. cin>>a[i];
  31. if(caut(1,n)==0)
  32. cout<<"Numarul cautat nu este pe nicio pozitie.";
  33. else
  34. cout<<"Numarul cautat este pe pozitia: "<<caut(1,n);
  35. return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement