title: Optimize Binary Search in sorted array find number of occurences
body: <p>Im trying to do the smallest number of operations possible to find the number of occurences of an element in the array. Save even 1 operation if possible. So far this is the best binary search version I know. <em><strong>I cant use vectors or any other std:: functions</strong></em></p>
  <pre><code>int modifiedbinsearch_low(int* arr, int low, int high , int key){   
      if(low==high) return high ; 
  
      int mid = low + (high-low) /2;
  
      if(key &gt;  arr[mid] ) { modifiedbinsearch_low(arr,mid + 1 , high,key);  } 
      else  { modifiedbinsearch_low(arr,low,mid,key);  }  
  }
  
  int modifiedbinsearch_high(int* arr, int low, int high , int key){   
      if(low==high) return high ; 
  
      int mid = low + (high-low) /2;
  
      if(key &lt;  arr[mid] ) { modifiedbinsearch_high(arr,low,mid,key);  } 
      else  { modifiedbinsearch_high(arr,mid+1,high,key);  } 
  
  } 
  
  int low = modifiedbinsearch_low( ...)
  int high = modifiedbinsearch_high( ...)
  </code></pre>
  <p>This version collapsed both functions into just one but it takes almost double the time. Im wondering the idea is good for it to become the fastest but the implementation is wrong.</p>
  <pre><code>#include&lt;stdio.h&gt;
  int binarysearch(int a[],int n,int k,bool searchfirst){
      int result=-1;
      int low=0,high=n-1;
      while(low&lt;=high){
          int mid=(low+high)/2;
          if(a[mid]==k)  {
                result=mid; 
             if(searchfirst)
                high=mid-1; 
              else
                low=mid+1;
      }
      else if(k&lt;a[mid])  high=mid-1;
      else low=mid+1;
      }
      return result;
  }
  
  int main(){
      int a[]={1,1,1,2,2,3,3,3,6,6,6,6,6,7,7};
      int n=sizeof(a)/sizeof(a[0]);
      int x=6;
      int firstindex=binarysearch(a,n,x,true);
      printf(&quot;%d\n&quot;,firstindex);
      if(firstindex==-1){
          printf(&quot;elment not found in the array:\n &quot;);
      }
      else {
          int lastindex=binarysearch(a,n,x,false);
          printf(&quot;%d\n&quot;,lastindex);
          printf(&quot;count is = %d&quot;, lastindex-firstindex+1);
      }
  
  }
  </code></pre>
  <p>Shorter version</p>
  <pre><code>      int  binmin(int a[], int start, int end,int val ) {
           if(start&lt;end) {
              int mid = (start+end)/2;
              if(a[mid]&gt;=val) 
                  binmin(a,start,mid-1,val);
              else if(a[mid]&lt;val)
                  binmin(a,mid+1,end,val);
  
        }
        else if(start&gt;end)
             return start;
  }
  </code></pre>