StefanAlexH

Binary search

Sep 20th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3.  
  4. int binary (int v [50], int s, int d, int n)
  5. {
  6.   if (s == d)
  7.   {
  8.     return s;
  9.   }
  10.   else if (s < d)
  11.   {
  12.     if (v [(s+ d) / 2] == n)
  13.     {
  14.       return ((s+ d) / 2) + 1 ; /*Conditia de oprire a loop-ului este gasirea elementului
  15.       cerut pe pozitia din mijloc*/
  16.     }
  17.     else if (v [(s+ d) / 2] < n)
  18.     {
  19.       return binary  (v, (s+ d) / 2 + 1, d, n); /*Daca vectorul e mai mare
  20.       decat elementul din mijloc, eliminam tot ce e in stanga mijlocului,
  21.       inclusiv*/
  22.     }
  23.     else if (v [(s+ d) / 2] > n)
  24.     {
  25.       return binary (v, d, (s+ d) / 2 - 1, n); // Analog ca mai sus
  26.     }
  27.   }
  28.   else
  29.   {
  30.     return -1;
  31.   }
  32.   return 0;
  33. }
  34.  
  35. int main ()
  36. {
  37.   int v [50];
  38.   int n;
  39.   int i;
  40.   int k;
  41.  
  42.   printf ("Introduceti numarul de elemente ale sirului: ");
  43.   scanf ("%d", &n);
  44.  
  45.   for (i = 0; i < n; i ++)
  46.   {
  47.     printf ("Introduceti elementul %d din vector, in ordine crescatoare ", i+1);
  48.     scanf ("%d", &v [i]);
  49.   }
  50.  
  51.   printf("Introduceti elementul cautat: ");
  52.   scanf("%d", &k);
  53.  
  54.   printf("Elementul %d se afla pe pozitia %d\n", k, binary(v, 0, n-1, k) );
  55.  
  56.   return 0;
  57. }
Add Comment
Please, Sign In to add comment