c - Search of an element on a unsorted array recursively -


this exercise took exam. asks write function receives unsorted array v[] , number x , function return 1 if x present in v[] or 0 if x not present in v[]. the function must recursive , must work in manner:

 1. compares x element in middle of v[];  2. function calls (recursion!!) on upper half , on lower half of v[]; 

so i've written function:

int occ(int *p,int dim,int x){      int pivot,a,b;     pivot=(dim)/2;      if(dim==0) //end of array         return 0;      if(*(p+pivot)==x) //verify if element in middle x         return 1;      a=occ(p,pivot,x); //call on lower half     b=occ(p+pivot,dim-pivot,x); //call on upper half      if(a+b>=1) //if x found return 1 else 0         return 1;     else{         return 0;     } } 

i tried simulated on sheet of paper , seems correct (even though i'm not sure) i've written on ideone , can't run program! here link: https://ideone.com/zwwpaw

is code wrong (probably!) or problem related ideone. can me? thank in advance!!!

the problem b=occ(p+pivot,dim-pivot,x); when pivot 0. i.e. when dim 1.

the next function call becomes occ(p,1,x); again leads call occ(p,1,x); in continuous loop.

it can fixed adding condition call, shown in code below.

int occ(int *p,int dim,int x){    int pivot,a=0,b=0;   pivot=(dim)/2;   if(dim==0){       return 0;   }    if(*(p+pivot)==x)       return 1;    if (pivot != 0)   {     a=occ(p,pivot,x);     b=occ(p+pivot,dim-pivot,x);   }    if(a+b>=1)       return 1;   else{       return 0;   } } 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -