Advertisement
Guest User

Untitled

a guest
May 30th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #define RECURSIVE   //da commentare o no a seconda se si vuole la versione ricorsiva o non
  4.  
  5. int i = 0;
  6.  
  7.  
  8.  
  9. /*****Versione non ricorsiva*****/
  10.  
  11. int cerca(int *v, int n, int x){
  12.     int a = 0, b = n;
  13.     while (a<b){
  14.         int half = (a+b)/2;
  15.         printf("iterazione %i, a = %i, b = %i, v[half = %i] = %i\n", i, a, b, half, v[half]);
  16.         i++;
  17.         if (v[half] == x) return 1;
  18.         if (v[half] < x) a = half+1;
  19.         else b = half;
  20.     }
  21.     return 0;  
  22. }
  23.  
  24. /*****End non rec*****/
  25.  
  26.  
  27.  
  28.  
  29. /*****Versione ricorsiva*****/
  30.  
  31. int rec_cerca(int *v, int n, int x, int a, int b){
  32.     if (a<b){
  33.         printf("Sono nell'if\n");
  34.         int half = (a+b)/2;
  35.         printf("iterazione %i| a = %i| b = %i| v[half = %i] = %i\n", i, a, b, half, v[half]);
  36.         i++;
  37.         if(v[half] == x) return 1;
  38.         if(v[half] < x) rec_cerca(v, n, x, half+1, b);
  39.         else rec_cerca(v, n, x, a, half);
  40.     }
  41.     printf("Sono uscito dall'if\n");
  42.     return 0;
  43. }
  44.  
  45. /*****End rec*****/
  46.  
  47.  
  48.  
  49.  
  50. int main(int argc, char* argv[]){
  51.     int i; 
  52.     int *v = malloc(100*sizeof(int));
  53.     int target = 57;
  54.     for(i=0; i<100; i++){
  55.         v[i] = 3*(i+1);
  56.         printf("| %i ", v[i]);
  57.     }
  58.     printf("|\n");
  59.  
  60.     #ifdef RECURSIVE
  61.     printf("Metodo ricorsivo\n");
  62.     int res = rec_cerca(v, 100, target, 0, 100);
  63.     #endif
  64.  
  65.     #ifndef RECURSIVE
  66.     printf("Metodo NON ricorsivo\n");
  67.     int res = cerca(v, 100, target);
  68.     #endif
  69.    
  70.     printf("Valore di res = %i\n", res);
  71.     if(res) printf("%i trovato!\n", target);
  72.     else printf("%i non trovato!\n", target);
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement