Count Element Occurence using c


#1

/**

  • @input A : Read only ( DON’T MODIFY ) Integer array
  • @input n1 : Integer array’s ( A ) length
  • @input B : Integer
  • @Output Integer
    */

int bin(int a[],int n,int x,int search)
{
int low=0,high=n-1,rslt=-1;
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]==x)
{
rslt=mid;
if(search)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
else if(x<a[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return rslt;
}

int findCount(const int* A, int n1, int B) {
int first=bin(A,n1,B,1);
if(first==-1)
{
return 0;
}
else
{
int last=bin(A,n1,B,0);
return(last-first+1);
}
}