Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int binary (int v [50], int s, int d, int n)
- {
- if (s == d)
- {
- return s;
- }
- else if (s < d)
- {
- if (v [(s+ d) / 2] == n)
- {
- return ((s+ d) / 2) + 1 ; /*Conditia de oprire a loop-ului este gasirea elementului
- cerut pe pozitia din mijloc*/
- }
- else if (v [(s+ d) / 2] < n)
- {
- return binary (v, (s+ d) / 2 + 1, d, n); /*Daca vectorul e mai mare
- decat elementul din mijloc, eliminam tot ce e in stanga mijlocului,
- inclusiv*/
- }
- else if (v [(s+ d) / 2] > n)
- {
- return binary (v, d, (s+ d) / 2 - 1, n); // Analog ca mai sus
- }
- }
- else
- {
- return -1;
- }
- return 0;
- }
- int main ()
- {
- int v [50];
- int n;
- int i;
- int k;
- printf ("Introduceti numarul de elemente ale sirului: ");
- scanf ("%d", &n);
- for (i = 0; i < n; i ++)
- {
- printf ("Introduceti elementul %d din vector, in ordine crescatoare ", i+1);
- scanf ("%d", &v [i]);
- }
- printf("Introduceti elementul cautat: ");
- scanf("%d", &k);
- printf("Elementul %d se afla pe pozitia %d\n", k, binary(v, 0, n-1, k) );
- return 0;
- }
Add Comment
Please, Sign In to add comment