Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. //binary search
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include <stdio.h>
  4. int main() {
  5. int n, v[100], st, dr,aux ,j, mij, x, gasit, i;
  6.  
  7. printf("Introduceti numarul de elemente: ");
  8. scanf("%d", &n);
  9. printf("Introduceti %d numere: \n", n);
  10.  
  11. for (i = 0; i < n; i++)
  12. scanf("%d", &v[i]);
  13.  
  14. for(i=0; i<n; i++)
  15. for(j=i; j<n; j++)
  16. if(v[i]< v[j])
  17. {
  18. aux = v[i];
  19. v[i] = v[j];
  20. v[j] = aux;
  21. }
  22. printf("Valoarea cautata in vector: ");
  23. scanf("%d", &x);
  24. gasit = 0;
  25. st = 0;
  26. dr = n - 1;
  27. while (st <= dr && gasit == 0)
  28. {
  29. mij = (st + dr) / 2;
  30. if (v[mij] == x)
  31. gasit = 1;
  32. else
  33. if (v[mij] > x)
  34. dr = mij - 1;
  35. else
  36. st = mij + 1;
  37. }
  38. if (gasit)
  39. printf("Numarul cautat exista in vector!");
  40. else
  41. printf("Numarul cautat nu exista in vector!");
  42.  
  43. return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement