首页 > 代码库 > 二分查找 变形

二分查找 变形

#include<stdio.h>

int solver(const int a[],const int n,const int t)
{
  int total = 0;
  if (NULL == a && 0 >= n)
      return total;
  int start = 0;
  int end = n-1;
  while(start <= end)
  {
   printf("%d   %d\n",start,end);
   int middle = (start + end)/2;
   if(t == a[middle])
   {
     total = 1;
     int cursor = 0;
     while(++cursor && middle + cursor < n && t == a[middle + cursor])
       total++;
     cursor = 0;
     while(--cursor && middle + cursor >= 0 && t == a[middle + cursor])
        total++;
     return total;
   }
   else if(t > a[middle])
    end = middle - 1;
   else
    start = middle + 1;
  }
  return total;
}

int main()
{
    int a[] = {1,1,1,1,1,1};
    int b[] = {1,2,2,2,2,3};
    int c[] = {1,2,3,5,6,7};
    printf("%d",solver(b,6,4));
}