int CountNumInSortArray(int a[],int n,int key)
{
if(a==NULL||n<=0)
throw exception("Invalid Input");
int i=0,j=n-1;
bool isFind=false;
while(i<=j)
{
int m=i+(j-i)/2;
if(a[m]<key)
i=m+1;
else if(a[m]>key)j=m-1;
else
{
j=m;
isFind=true;
if(i==j)
break;
}
}
cout<<i<<endl;
int start;
if(isFind)
start=i;
else
return -1;
j=n-1;
while(i<j-1)
{
int m=i+(j-i)/2;
if(a[m]<key)
i=m+1;
else if(a[m]>key)j=m-1;
else
{
i=m;
}
}
int end;
if(i+1==j&&a[i]==a[j])
{
end=j;
}
else
end =i;
return end-start+1;
}
void main()
{
int a[]={1,2,3,3,3,3,4,5};
try
{
int num=CountNumInSortArray(a,8,5);
if(num==-1)
cout<<"Can not find!"<<endl;
else
cout<<num<<endl;
}
catch(exception e)
{
cout<<e.what()<<endl;
}
system("pause");
}