Why is this code giving wrong answer?


#1
int i=0, j=a.size()-1, mid, ans=0;
while(i<=j){
	mid = (i+j)/2;
	if(a[mid]==b) {ans++; break;}
	else if(a[mid]<b) i=mid+1;
	else j=mid-1; 
}
i=mid-1; j=mid+1;
while(a[i]==b) {ans++; i--;}
while(a[j]==b) {ans++; j++;}
return ans;

#2

ur code complexity is O(n) ur doing linear search in last 2 while loops see for worst case scenario; what if all elements are same